How to play only one sound at the same time ?
Im creating a soundboard game and i want to play only one sound at the same time. When I press another button I want to stop the first sound and play second sound. What should I do ? Sorry for my English :/
using UnityEngine; using System.Collections; using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class ClickSound : MonoBehaviour {
public AudioClip sound;
private Button button { get { return GetComponent<Button> (); } }
private AudioSource source { get { return GetComponent<AudioSource> (); } }
void Start ()
{
gameObject.AddComponent<AudioSource> ();
source.clip = sound;
source.playOnAwake = false;
button.onClick.AddListener (() => PlaySound ());
}
void PlaySound ()
{
source.PlayOneShot (sound);
}
}
Answer by HenryStrattonFW · Jan 18, 2017 at 09:32 PM
All you need to do is swap "PlayOneShot" for "Play", and also it's probably best to put a source.Stop() call just before you set the clip on the source, so basically the logic flows as such:
Stop sound currently playing.
Change to new sound.
Play new sound.
EDIT: Had another read over your code and realised I missed the point a bit first time around (sorry about that) I'm assuming that this component you've written is on all of your buttons. In that case I would suggest you store the currently playing button in a static variable when you play a sound. That way when you try to press a new button, you can check this value, ensure the sound on it is stopped, and then play your new sound before then setting that button as the last active button. Here's some code that should do the trick.
private static ClickSound lastClickSound;
void PlaySound()
{
if (lastClickSound != null && lastClickSound.source != null)
{
lastClickSound.source.Stop();
}
source.Play();
lastClickSound = this;
}
You're welcome. good luck with your soundboard project.
Your answer
![](https://koobas.hobune.stream/wayback/20220612105111im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make audio play at once. 1 Answer
Cracking at end of audio? 0 Answers
Audio not playing when destroying a GameObject. 1 Answer
Need help: new sound isnt played correctly anymore 2 Answers