private void PlayNextBackground()
{
if (this.fmodSystem == null)
return;
// Find next background track
if (this.backgroundAudioTracks.Count == 0)
// No tracks
return;
int index;
while (true)
{
index = this.random.Next(this.backgroundAudioTracks.Count - 1);
if (this.backgroundAudioTracks.Count > 1 && this.currentBgTrack == index)
continue;
break;
}
this.currentBgTrack = index;
string fileName = this.backgroundAudioTracks[index];
this.currentBgTrackName = Path.GetFileName(fileName);
this.log.Info("Play background track {0}", Path.GetFileName(fileName));
var sound = this.fmodSystem.CreateStream(fileName, Mode.Default);
try
{
var chn = this.currentBgChannel;
if (chn.HasValue)
{
// Make sure we reset this first so we can ignore the callback
this.currentBgChannel = null;
chn?.Stop();
}
}
catch (FmodInvalidHandleException)
{
// Ignore
}
if (this.currentBgSound.HasValue)
this.disposeList.Add(this.currentBgSound);
this.currentBgSound = null;
var channel = this.fmodSystem.PlaySound(sound, this.bgGroup, true);
string bgName = this.currentBgTrackName;
channel.SetCallback((type, data1, data2) =>
{
if (type == ChannelControlCallbackType.End)
{
this.log.Debug("Background {0} ended", bgName);
SendMessage(new AudioFinished
{
Id = bgName,
Type = AudioTypes.Background
});
if (this.currentBgChannel.HasValue)
PlayNextBackground();
}
});
this.currentBgSound = sound;
this.currentBgChannel = channel;
// Play
channel.Pause = false;
SendMessage(new AudioStarted
{
Id = bgName,
Type = AudioTypes.Background
});
}