Queueing audio

Let’s say I have 2-3 songs that I want to play one after another. I am very close to implementing, but I have a little problem when switching those. They are of type AudioSource.

function controlMusic()
{	
	// Toggle music
	if(Input.GetKeyDown("m"))
	{
		music1.mute = !(music1.mute);
		music2.mute = !(music2.mute);
	}
	
	if (!(music1.isPlaying || music2.isPlaying))
	{
		switch (currentMusic)
		{
			case 1:
			music1.Play();
			break;
			
			case 2:
			music2.Play();
			break;
		
		}
		currentMusic++;
		if (currentMusic > 2) currentMusic = 1;
	}
}

My problem is that this code doesn’t work normally. However if I go to inspector during runtime and set music1 inactive(by clicking the tick), then it performs the switch.

Ok let’s get it back to the beginning.

public AudioSource [] audioSource;
int index = 0;
void Start()
{
   audio.clip = audioSource[index];
   StartCoroutine(PlaySong());
}

IEnumerator PlaySong()
{
    while(true)
    {
        if(!audio.isPlaying)
        {
            if(++index == audioSource.Length)index = 0;
            audio.clip = audioSource[index];
            audio.Play();
        }
        yield return null;
    }
}

Try this since I have not…

What it does now: First you have the array and an index. In the Start, you set the clip to be the first one. Then you start a coroutine that will play non-stop.

The coroutine is an infinite while loop which gets out every frame. In between, it checks whether the music is playing. If the music stops because we reached the end of the clip, the index is increased and checked against the length of the array. New clip is passed and play.

Sorry that this is in C#, but I was a bit in a rush to get this done. It’s explained fully, so if you don’t know C# it won’t be hard to understand.

/* Save under MusicRandomizer.cs */
using UnityEngine;
using System.Collections;

public class MusicRandomizer : MonoBehavior
{
	private int curAudio = 0;
	// Current audio file selected, out of an array.
	// Inside of a C# array, the first element is listed as [0],
	// so we set curMusic to 0
	
	public AudioClip[] clips; // Define in editor
	
	private void Update()
	{
	
		if(!gameObject.audio.clip.isPlaying)
		// If no audio is playing
		{
		
			if(curMusic > clips.Length)
			{
				curAudio = 0;
				// If curAudio is higher than your total clips, set back to 0
			}
			
			gameObject.audio.clip = clips[curAudio];
			// Set game objects audio clip
			
			gameObject.audio.clip.Play();
			// Play game objects audio clip
			
			curAudio++;
			// Increment curAudio
		}
		
	}
	
}