//Play from currently loaded Music List public bool PlayAudio(int index) { if (currentPlaying == null) { currentPlaying = musicData[index]; audioSource.clip = currentPlaying.audioClip; audioSource.Play(); return(true); } else if (index >= musicData.Length) { return(false); } else if (musicData[index].id == currentPlaying.id) { return(false); } StartCoroutine(StartNewMusic(musicData[index])); return(true); }
//Coroutine to fade music in/out private IEnumerator StartNewMusic(MusicData newAudio) { while (audioSource.volume > 0) { audioSource.volume -= Time.deltaTime * 2; yield return(new WaitForEndOfFrame()); } audioSource.Stop(); currentPlaying = newAudio; audioSource.clip = currentPlaying.audioClip; audioSource.timeSamples = 0; audioSource.Play(); while (audioSource.volume < volumeMax) { audioSource.volume += Time.deltaTime * 2; yield return(new WaitForEndOfFrame()); } audioSource.volume = volumeMax; }