Hello all, i was wondering how i can play music from a playlisrt without replaying something that has already been played. Here is my script for playing music randomly from a playlist.
using UnityEngine;
using System.Collections;
public class musicPlayer : MonoBehaviour {
public AudioClip[] clips;
private AudioSource audioSource;
// Use this for initialization
void Start () {
audioSource = FindObjectOfType<AudioSource>();
audioSource.loop = false;
}
private AudioClip GetRandomClip()
{
return clips[Random.Range(0, clips.Length)];
}
// Update is called once per frame
void Update () {
if(!audioSource.isPlaying)
{
audioSource.clip = GetRandomClip();
audioSource.Play();
}
}
}
Assign shuffled numbers between 0 and clips.Length to this integer array. Search for a sorting algorithm or use the just-made-up-untested-sorting-algorithm presented below.
Play the next song in normal order getting the index from your shuffled array.
Rough untested code to be used as guideline:
int[] songList[clips.Length];
int songIndex = 0;
for (i=0; i=clips.Length; i++) {
songList *= i;*
} for (int i = 0; i <= clips.Length; i++) { int tempIndex = Random.Range(i, clips.Length); int tempSongNumber = songList[tempIndex]; for (int k = tempIndex; k >= (i+1); k–) { songList[k] = songList[k - 1]; } songList = tempSongNumber; } audioSource.clip = clips(songList(songIndex)); audioSource.Play(); songIndex++;