- Home /
Play music in Unity without repeating a song
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();
}
}
}
Answer by guneyozsan · Nov 04, 2016 at 11:35 PM
Create an integer array of length clips.Length
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] = 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[i] = tempSongNumber;
}
audioSource.clip = clips(songList(songIndex));
audioSource.Play();
songIndex++;
What's the point of the inner for-loop? It's enough to simply swap the element at "i" with the element at tempIndex. Also this "shuffelling" could be done without the seperate "index array".
Anyways your solution should work as well, so +1
ps.: k >= (i+1)
would be the same as k > i
Answer by aditya · Nov 03, 2016 at 08:05 AM
I think you are searching for something like AudioSource.time
Accept if it helped