by Wojciech Sura

How to write an MP3 player?

Impressing friends when you’re a programmer is actually quite a hard task. We have to accept the fact, that the overwhelming majority of the population associates the word “class” with a chalkboard and mostly probably won’t see the beauty of, for instance, virtual treeview control boosted up by item position cache, which is generated dynamically on request in a separate thread. Sigh.

So let’s try something simpler and easier to show our non-technical friends: we’ll write an mp3 player in just nice round 16 lines of code.

You’ll need NAudio package.


Create an empty Windows Forms project and let’s write our 16 lines.  First of all, add two using’s to the code.
[csharp]using NAudio;
using NAudio.Wave;[/csharp]
You’ll have to add the following fields to the form class.
[csharp]private IWavePlayer waveOut;
private AudioFileReader reader;
Then initialize the waveOut object in form’s constructor.
[csharp]public Form1()
waveOut = new WaveOut();
Create two buttons on the form. Call first “Open and play” and second “Stop”. Now implement first button’s Click event:
[csharp]private void button1_Click(object sender, EventArgs e)
OpenFileDialog openDialog = new OpenFileDialog()
Filter = "Music files (*.mp3)|*.mp3"

if (openDialog.ShowDialog() == DialogResult.OK)
reader = new AudioFileReader(openDialog.FileName);
Finally, implement second button’s Click event:
[csharp]private void button2_Click(object sender, EventArgs e)
And that’s all! Compile the application and run. Enjoy!

Tags: , ,