- Home /
Randomly mp3 sript, playing just first song
Hi, please help me with this i don't know what i'm doing bad. I'm trying to make music, that play randomly, but i don't know how to do that. Thanks.
using UnityEngine;
using System.Collections;
public class Music : MonoBehaviour {
public Object[] myMusic; // declare this as Object array
void Awake () {
myMusic = Resources.LoadAll("Music",typeof(AudioClip));
GetComponent<AudioSource>().clip = myMusic[0] as AudioClip;
}
void Start (){
GetComponent<AudioSource>().Play ();
}
// Update is called once per frame
void Update () {
if(!GetComponent<AudioSource>().isPlaying)
playRandomMusic();
}
void playRandomMusic() {
GetComponent<AudioSource>().clip = myMusic[Random.Range(0,myMusic.Length)] as AudioClip;
GetComponent<AudioSource>().Play();
}
}
To me, that seems over complicated, I wouldnt do the whole resources stuff. Id keep it simple:
public AudioClip[] playList;
void Start (){
playRandom$$anonymous$$usic();
}
void playRandom$$anonymous$$usic() {
GetComponent<AudioSource>().clip = playList[Random.Range(0,playList.Length - 1)];
GetComponent<AudioSource>().Play();
}
Then every time you run your application, it will randomly play a track, but its possible you could get the same "random" track 2 or 3 times in a row, because of how the Random class works.
Well, make sure that the object you have this script on, 1. Has an audio source, and 2. the script has audio clips/mp3 files in its array, then it should work fine with no problems.
Answer by InfernoZYB · Jul 14, 2015 at 01:16 AM
Hmmm Try using an audioclip insted of an object. Try this. Never tried this but should work.
public AudioClip[] Sounds;
void Update(){
if(!GetComponent<AudioSource>().isPlaying){ PlayRandomMusic(); }
}
void PlayRandomMusic(){
int i = (int)Random.Range (0, Sounds.Length);
GetComponent<AudioSource>().PlayOneShot(Sounds[i], 1F);
}
this script makes that, all song are playing together... but thanks