Kurru
Kurru

Reputation: 14331

NAudio playback won't stop successfully

When using NAudio to playback an MP3 file [in the console], I can't figure out how to stop the playback. When I call waveout.Stop() the code just stops running and waveout.Dispose() never gets called.

Has it something to do with the function callback? If it is, how do I fix it?

static string MP3 = @"song.mp3";
static WaveOut waveout;
static WaveStream playback;
static void Main(string[] args)
{
    waveout = new WaveOut(WaveCallbackInfo.FunctionCallback());
    playback = OpenMp3Stream(MP3);
    waveout.Init(playback);
    waveout.Play();
    Console.WriteLine("Started");

    Thread.Sleep(2 * 1000);

    Console.WriteLine("Ending");
    if (waveout.PlaybackState != PlaybackState.Stopped)
        waveout.Stop();
    Console.WriteLine("Stopped");
    waveout.Dispose();
    Console.WriteLine("1st dispose");
    playback.Dispose();
    Console.WriteLine("2nd dispose");
}
private static WaveChannel32 OpenMp3Stream(string fileName)
{
    WaveChannel32 inputStream;
    WaveStream mp3Reader = new Mp3FileReader(fileName);
    WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
    WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);
    inputStream = new WaveChannel32(blockAlignedStream);
    return inputStream;
}

Upvotes: 3

Views: 3870

Answers (2)

Mark Heath
Mark Heath

Reputation: 49522

Are you saying the code hangs in the call to waveOutReset? If so, this is a known issue with function callbacks and certain audio drivers (SoundMAX seems particularly susceptible to this). I checked in a possible fix to the NAudio source code a couple of months ago, so you could try building the latest code and seeing if that fixes the issue.

Upvotes: 5

Mitchel Sellers
Mitchel Sellers

Reputation: 63136

My first guess here is that since you have no console.read() or similar call that your code is just executing so fast that you don't see the final write lines.

If NAudio implements IDisposable then i would recommend using a using statement to have .NET handle this for you.

Upvotes: 0

Related Questions