- Home /
Question by
soof · Aug 11, 2015 at 12:59 AM ·
audioaudiosourceplaynext
Play next song
public class Music : MonoBehaviour {
Object[] pMusic;
void Awake () {
pMusic = Resources.LoadAll("Music",typeof(AudioClip));
GetComponent<AudioSource>().clip = pMusic[0] as AudioClip;
}
void Start (){
GetComponent<AudioSource>().Play();
}
Im sure this is a simple question but how do write a script for playing the next song in the directory.
Comment
Answer by nullgobz · Aug 11, 2015 at 01:16 AM
I have not tested this code.
AudioClip[] pMusic;
int currentTrack;
int totalTracks;
AudioSource source;
void Awake()
{
pMusic =(AudioClip[])Resources
.LoadAll("Music", typeof(AudioClip));
source = GetComponent<AudioSource>();
totalTracks = pMusic.Length;
}
void Start()
{
if(totalTracks > 0)
SwitchTrack();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
SwitchTrack();
}
void SwitchTrack()
{
if(source.isPlaying)
source.Stop();
if(currentTrack >= totalTracks)
currentTrack = 0;
source.clip = pMusic[currentTrack++];
source.Play();
}
im not 100% sure but it may need to say more about current track?
I tweaked it and got it to work with this
using UnityEngine; using System.Collections; using System.IO; using System.Linq; using UnityEngine.UI;
public class $$anonymous$$usic : $$anonymous$$onoBehaviour {
public Text $$anonymous$$usicListText;
private string display = "";
Object[] m$$anonymous$$usic;
int currentTrack;
int totalTracks;
AudioSource source;
void Awake () {
m$$anonymous$$usic = Resources.LoadAll("$$anonymous$$usic",typeof(AudioClip));
source = GetComponent<AudioSource> ();
source.clip = m$$anonymous$$usic[0] as AudioClip;
totalTracks = m$$anonymous$$usic.Length;
}
void Update (){
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
SwitchTrack();
}
void SwitchTrack()
{
if(source.isPlaying)
source.Stop();
if(currentTrack >= totalTracks)
currentTrack = 0;
source.clip = m$$anonymous$$usic[currentTrack++] as AudioClip;
source.Play();
}
Your answer
Follow this Question
Related Questions
Audio continuation through two scenes 3 Answers
Playing Sound 2 Answers
Audio clip not playing 1 Answer
Active audiosource change on button press. Making a ingame radio. 1 Answer
Audio playing problem 1 Answer