Thursday, 24 April 2014

Playing Audio using NAudio 1.7.1

I hope that this post saves people some searching when it comes to playing audio files using NAudio version 1.7.1.
The reason I switched to NAudio for Sapphire was because of Windows Media Players notorious memory leak problem, being a COM object that is accessed via a wrapper is bound to lead to problems. In my case it's an Out of Memory exception each morning when the alarm fires. The easiest way to play and audio file is as follows.

//Media FoundationReader is capable of playing MP3,AAC,WAV,FLAC
//as well as Network Streams
//Create a reader and pass either Local Uri or a Network URL
MediaFoundationReader reader = new MediaFoundationReader("PATH");
WaveOutputStream streamOut = reader;
//Create a 32bit output channel that you use for volume control
//ex: volumeStream.Volume = 0.5; //Float 0-1
WaveChannel32 volumeStream = new WaveChannel32(streamOut);
//Use WaveOutEvent vs WaveOut since the former works in every case from;
//background to UI
WaveOutEvent player = new WaveOutEvent();
//Initialize with volumeStream from this point player is ready
player.Init(volumeStream);
player.Play();

To reuse the player just call Dispose() on player, volumeStream, and reader then set them to null before attempting to play a different media source or file.

No comments:

Post a Comment