简体   繁体   中英

unity c# - replay sounds overlapping

I have a code here which automatically plays a sound when target is found and stops when target is lost. What I'm doing is that I want to repeat the sound of the target currently found. The problem is when i click the replay button, the sound of the last target found, and the current target are both playing.

I coded this on the DefaultTrackableEventHandler script. Here's my code:

public AudioSource soundTarget;
public AudioClip clipTarget;
private AudioSource[] allAudioSources;
public Button Button;

void StopAllAudio()
    {
        allAudioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
        foreach (AudioSource audioS in allAudioSources)
        {
            audioS.Stop();

        }
    }

void playSound(string ss)
    {
        clipTarget = (AudioClip)Resources.Load(ss);
        soundTarget.clip = clipTarget;
        soundTarget.loop = false;
        soundTarget.playOnAwake = false;
        soundTarget.Play();

    }

public void ReplayAudio()
    {
        soundTarget.PlayOneShot(clipTarget);
    }

Under public virtual void OnTrackingFound()

    public virtual void OnTrackingFound()
    {

  if (mTrackableBehaviour.TrackableName == "letterA")
        {
            playSound("sounds/airplane");

            Button.onClick.AddListener(ReplayAudio);
        }

        if (mTrackableBehaviour.TrackableName == "letterB")
        {
            playSound("sounds/banana");

            Button.onClick.AddListener(ReplayAudio);
        }

//On trackingLost: StopAllAudio();

You need to call RemoveAllListeners on your button before adding another listener or they will stack everytime a target is found.

public virtual void OnTrackingFound()
{
  Button.onClick.RemoveAllListeners();

  if (mTrackableBehaviour.TrackableName == "letterA")
  {
      playSound("sounds/airplane");
      Button.onClick.AddListener(ReplayAudio);
  }

  if (mTrackableBehaviour.TrackableName == "letterB")
  {
      playSound("sounds/banana");
      Button.onClick.AddListener(ReplayAudio);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM