Skip to content

Instantly share code, notes, and snippets.

@LiamDobbelaere
Created February 27, 2019 23:08
Show Gist options
  • Save LiamDobbelaere/a97e54fc379090da02ee9c214c371654 to your computer and use it in GitHub Desktop.
Save LiamDobbelaere/a97e54fc379090da02ee9c214c371654 to your computer and use it in GitHub Desktop.
This Unity behaviour acts as a music playlist, crossfading and looping through an entire audio playlist
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicPlayer : MonoBehaviour
{
private AudioSource aTrack;
private AudioSource bTrack;
private bool aTrackIsMain;
private float maxTrackVolume = 0.5f;
private float lastATime;
private float lastBTime;
public AudioClip[] playlist;
int playlistPos = 0;
int rollOvers = 0;
// Start is called before the first frame update
void Start()
{
var sources = GetComponents<AudioSource>();
aTrack = sources[0];
bTrack = sources[1];
aTrackIsMain = true;
aTrack.volume = 0f;
bTrack.volume = 0f;
aTrack.clip = playlist[playlistPos];
aTrack.Play();
bTrack.clip = playlist[playlistPos];
bTrack.Play();
}
int GetNextPlaylistIndex()
{
var value = playlistPos;
if (playlistPos + 1 >= playlist.Length) return 0;
else return playlistPos + 1;
}
// Update is called once per frame
void Update()
{
if (aTrackIsMain)
{
aTrack.volume = Mathf.Lerp(aTrack.volume, maxTrackVolume, Time.deltaTime);
bTrack.volume = Mathf.Lerp(bTrack.volume, 0f, Time.deltaTime);
if (aTrack.time < lastATime)
{
rollOvers += 1;
}
}
else
{
aTrack.volume = Mathf.Lerp(aTrack.volume, 0f, Time.deltaTime);
bTrack.volume = Mathf.Lerp(bTrack.volume, maxTrackVolume, Time.deltaTime);
if (bTrack.time < lastBTime)
{
rollOvers += 1;
}
}
lastATime = aTrack.time;
lastBTime = bTrack.time;
if (rollOvers > 1) NextTrack();
}
void NextTrack()
{
rollOvers = 0;
playlistPos = GetNextPlaylistIndex();
aTrackIsMain = !aTrackIsMain;
if (aTrackIsMain)
{
lastATime = 0f;
aTrack.clip = playlist[playlistPos];
aTrack.Play();
}
else
{
lastBTime = 0f;
bTrack.clip = playlist[playlistPos];
bTrack.Play();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment