Preventing an Audio Clip from restarting if it is already playing

In a game, there may be several different events that cause a sound to start playing. If the sound is already playing, then in almost all cases, we won't wish to restart the sound. This recipe includes a test, so that an Audio Source component is only sent a Play() message if it is currently not playing.

Getting ready

Try this with any audio clip that is one second or longer in duration. We have included the engineSound audio clip inside the 1362_09_03 folder.

How to do it...

To prevent an Audio Clip from restarting, follow these steps:

  1. Create an Empty GameObject and rename it to AudioObject. Then, add an Audio Source component to this object (in the Component | Audio | Audio Source menu).
  2. Import the engineSound audio clip and drag it from the Project view to populate the Audio Clip parameter of the Audio Source component of AudioObject:
    How to do it...
  3. Create a UI button named PlaySoundButton on the screen and attach the following script to this button:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    public class AvoidEarlySoundRestart : MonoBehaviour {
      public AudioSource audioSource;
      public Text message;
    
      void Update(){
        string statusMessage = "Play sound";
        if(audioSource.isPlaying)
          statusMessage = "(sound playing)";
        message.text = statusMessage;
      }
    
      // button click handler
      public void PlaySoundIfNotPlaying(){
        if( !audioSource.isPlaying)
          audioSource.Play();
      }
    }
  4. With PlaySoundButton selected in the Hierarchy panel, drag AudioObject into the Inspector view for the public Audio Source variable, and drag the Text child of PlaySoundButton for the public ButtonText:
    How to do it...
  5. With PlaySoundButton selected in the Hierarchy panel, create a new on-click event handler, dragging the PlaySoundButton into the Object slot, and selecting the PlaySoundIfNotPlaying() function.

How it works...

The Audio Source components have a public readable property isPlaying, which is a Boolean true/false flag, indicating if the sound is currently playing. The text of the button is set to display Play Sound when the sound is not playing, and (sound playing) when it is. When the button is clicked, the PlaySoundIfNotPlaying() method is called. This method uses an if statement, ensuring that a Play() message is only sent to the Audio Source component if its isPlaying is false.

See also

  • The Waiting for the audio to finish before auto-destructing an object recipe in this chapter.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.203.96