Reputation: 265
So currently I have an audio clip that is 8 seconds long. However I want to be able to stop it from playing when specific things happen. Something like this:
private AudioSource soundPlayer2D;
private AudioClip sound;
void Start(){
GameObject new2DsoundPlayer = new GameObject ("2DSoundPlayer");
soundPlayer2D = new2DsoundPlayer.AddComponent<AudioSource> ();
new2DsoundPlayer.transform.parent = transform;
}
void Update() {
if(shouldPlayAudio){
soundPlayer2D.PlayOneShot (sound, fxVolumePercentage * allVolumePercentage);
} else if(shouldStopAudio){
//Stop Audio <--
}
}
Edit 1: Note I only want to stop the specific audio clip and not the Audio Source
Upvotes: 9
Views: 16829
Reputation: 11
You can always use the mute property on your audiosource.mute property to stop the incoming sound. It wont stop playing the clip but it will stop the sound of clip coming from your game.
in your case
soundPlayer2D.mute = true;
Upvotes: 0
Reputation: 125285
You can't stop Audio when PlayOneShot
is used. It's like play and forget function. Of-course you can mute Unity's Audio System, but that's not a good solution.
You need to use the Play function instead. Simply assign the AudioClip to AudioSource then play it. It can now be stopped with the Stop function.
private AudioSource SoundPlayer2D;
private AudioClip sound;
Before playing, assign the AudioClip to the AudioSource
SoundPlayer2D.clip = sound;
Now, you can play it
SoundPlayer2D.Play();
And stop it:
SoundPlayer2D.Stop();
It's never a good idea to decide when to play an audio with a boolean
variable. Don't do this because you will run into problems such as audio not playing because you are trying to play it multiple times in a frame.
You need to put that in a function that plays and stops the audio.
Something like this:
public void playMyAudio(AudioClip clipToPlay)
{
SoundPlayer2D.clip = clipToPlay;
SoundPlayer2D.Play();
}
public void stopMyAudio()
{
SoundPlayer2D.Stop();
}
and soundPlayer2D should solely be devoted to playing the sound AudioClip?
Nope. You don't have to unless you need multiple audios to be playing at the-same time. You can always change AudioSource (soundPlayer2D
) clip to another AudioClip
before playing it.
Upvotes: 11