Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop an audio when PlayOneShot is used

Tags:

c#

unity3d

audio

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

like image 747
RaZ Avatar asked Mar 08 '23 13:03

RaZ


1 Answers

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.

like image 199
Programmer Avatar answered Mar 30 '23 04:03

Programmer