MP3
Playing an MP3
1) Add the following using statements to your project:
using NAudio; using NAudio.Wave;
2) Create the declarations in your class:
//Declarations required for audio out and the MP3 stream IWavePlayer waveOutDevice; WaveStream mainOutputStream;
WaveChannel32 volumeStream;
3) In a method – that only needs to be called once, setup the waveOutDevice. In this example we will use WaveOut, since it is the most universally available. If you are not playing audio from within
a WinForms or WPF application, then WaveOutEvent may be a better choice.
waveOutDevice = new WaveOut();
4) Load the MP3 file in the same method
mainOutputStream = CreateInputStream("Horrorshow - Thoughtcrime (Doin' My Think).mp3");
5) The CreateInputStream method has been lifted from the NAudioDemo project but the important elements have been replicated here for completeness
private WaveStream CreateInputStream(string fileName) { WaveChannel32 inputStream; if (fileName.EndsWith(".mp3")) { WaveStream mp3Reader = new Mp3FileReader(fileName); inputStream = new WaveChannel32(mp3Reader); } else { throw new InvalidOperationException("Unsupported extension"); } volumeStream = inputStream; return volumeStream; }
6) Init the device and call play – again this also only needs to be called once.
waveOutDevice.Init(mainOutputStream); waveOutDevice.Play();
7) That’s all there is to it. A MP3 playing from your application.
To clean up the code remove the references etc.
private void CloseWaveOut() { if (waveOutDevice != null) { waveOutDevice.Stop(); } if (mainOutputStream != null) { // this one really closes the file and ACM conversion volumeStream.Close(); volumeStream = null; // this one does the metering stream mainOutputStream.Close(); mainOutputStream = null; } if (waveOutDevice != null) { waveOutDevice.Dispose(); waveOutDevice = null; } }