ekolis
ekolis

Reputation: 6814

Why does my NAudio music freeze when CPU usage spikes in my game?

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

Answers (1)

Mark Heath
Mark Heath

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:

  1. Operate at a higher latency
  2. Minimise the work the audio engine needs to do (e.g. pre-decompress audio from custom formats to PCM and store it in memory)

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

Related Questions