Reputation: 6814
I'm writing a game and trying to use NAudio to play music and sound effects, but when the game uses a lot of CPU, the music freezes. I tried running the music in a separate thread, but that didn't seem to help. How can I prevent the music from freezing?
Here's my music playback code:
// (code to select a track goes here)
// prepare the new track
var tl = trackname.ToLower();
var path = Path.Combine("Music", trackname);
IWaveProvider p;
if (tl.EndsWith("ogg"))
p = new VorbisWaveReader(path);
else if (tl.EndsWith("mp3"))
p = new Mp3FileReader(path);
else if (tl.EndsWith("wav"))
p = new WaveFileReader(path);
else
throw new Exception("Unknown audio format for file " + path);
waveout.Stop();
if (CurrentMode == MusicMode.None)
return; // no music!
// fade between the two tracks
prevTrack = curTrack;
if (prevTrack != null)
prevTrack.BeginFadeOut(FadeDuration);
curTrack = new FadeInOutSampleProvider(p.ToSampleProvider(), true);
curTrack.BeginFadeIn(FadeDuration);
// start playing
// TODO - start fade of new track even before old track is done?
if (prevTrack != null)
waveout.Init(new MixingSampleProvider(new ISampleProvider[] { curTrack, prevTrack }));
else
waveout.Init(curTrack);
waveout.Play();
waveout.PlaybackStopped += waveout_PlaybackStopped;
Upvotes: 0
Views: 540
Reputation: 49522
What type is WaveOut
? Using WaveOutEvent
will do the audio on a background thread.
Also, calling WaveOut.Init
a second time on the same WaveOut
instance is not something officially supported by NAudio and may result in strange things happening.
The main ways to improve audio performance are:
Probably for your scenario the best thing would be to create a custom cross-fading sample provider. Unfortunately there is not one in NAudio at the moment, but it's a good idea for a future blog post / code sample, so I'll put it on the list of things to write about.
Upvotes: 1