Stop audiosource clip from playing

Hi,

When a condition happens I play an audio clip but I also want it to stop on a certain condition and play another clip. The problem is that I do not know how to stop this clip from playing. Code:

if(i == 0){
     i=1;
     AudioSource.PlayClipAtPoint(breathing1, transform.position);
     yield WaitForSeconds(2);
     audio.Stop();
     Debug.Log("stop sound");
}

Unfortunately, I don’t think you can stop PlayClipAtPoint unless you find it as a gameObject and destroy it. Aldo has covered this topic here : Adjust properties of AudioSource created with PlayClipAtPoint - Questions & Answers - Unity Discussions

Is there any reason you have to use PlayClipAtPoint and not a permanent audioSource that you just use audio.Stop(); and change the audioClip ?


Edit :

  • Create an empty GameObject > Create empty
  • Attach the Component Audio > Audio Source
  • un-tick Play on Awake
  • Attach the below script, then drop sounds in the Inspector.
  • press play
  • hit 1 or 2 . The audio should stop, change clip and play the selected sound.

Script :

#pragma strict

var clip1 : AudioClip;
var clip2 : AudioClip;

function Start() 
{
	audio.Stop(); // just incase PlayOnAwake is ticked
}

function Update() 
{
	if ( Input.GetKeyDown(KeyCode.Alpha1) )
	{
		audio.Stop();
		audio.clip = clip1;
		audio.Play();
	}
	
	if ( Input.GetKeyDown(KeyCode.Alpha2) )
	{
		audio.Stop();
		audio.clip = clip2;
		audio.Play();
	}
}

Here is a video on audio source : Unity 3D Student - 3d Modelling

If you use this method, just make the empty gameObject with the audio as a child of your character, then everywhere the character goes, the sound follows. PlayClipAtPoint is usually to play a ricochet sound at the point the bullet hit an object, or other similar scenarios where you only want one sound at a position to play once only (then gets destroyed, pretty much the same as PlayOneShot).