Stop and start audio using c#

Hi so I have a disco in a game that plays music and I have speakers around the room that I want the audio to source from. However, I wanted to set up a DJ booth where you can change the song playing via some buttons you click on or press a button. As I am new to unity, I don’t know how I can get the button object to stop the current audio and play a new audio (keep in mind the audio is attached to the speaker objects)

Any help would be appreciated. :slight_smile:

Hiho

Try to use:

if(GUI.Button(new Rect(50, 50, 50, 50), "Play"){
audio.Play();
}

Also take a look in these links:

Audio Clip

Audio Component

Audio Source

First, you have to add a reference to your speaker that contains the audio source, in the script that handles the button clicks.

Let’s say you have a on/off button object in the DJ box, then you would create the following script and attach it to the button object in your scene:

public class MusicOnOffScript : MonoBehaviour {
    public GameObject speakersGameobj;

    public void Start() {
    }

    void Update() {
		// check if mouse clicked
		if (Input.GetKeyDown("mouse 1")) {
		
			// check if mouse clicked this object
			Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);       // get ray from camera to mouse position
			RaycastHit hitInfo;
			Physics.Raycast(mouseRay, out hitInfo);										// raycast from camera to mouse position
			
			// check if ray from camera to mouse position hit this button
			if (hitInfo.collider == this.collider) {
			
				// toggle audio on/off on audiosource of speakers
				AudioSource source = speakersGameObj.GetComponent<AudioSource>();
				source.mute = !source.mute;
			}
		}
    }
}

Then, in the editor, select the on/off button object. You’ll see the script in the inspector, and a placeholder for “Speakers Gameobj”. Drag & drop the speakers object into it. This creates a reference in the button script to the speakers object.

Then notice the AudioSource source = ... command in the script. It fetches the AudioSource component from the Speakers game object that it references. Then it’s as simple as setting the mute property. (you can use Start() / Stop() if you prefer it over muting).

Good luck