Introduction
In this article I describe how to play audio in C# .Net. There are several ways to create a player in C# but in this article I will describe the simplest way to create a MP3 player that plays .mp3 and .wav files only, because I set the Filter property of the opendialog box.
Use the following procedure to create it.
Step 1
Open Visual Studio 2010
"File" -> "New" -> "Project..."
Choose "Template" -> "Visual C#" -> "Windows Form Application "
Step 2
Now add the windows Media Player control in your Toolbox.
Right-click in toolbox
Select "Choose items"
Look for the Windows Media Player within the "COM components" tab of the Choose toolbox Items window
Note: Now the Windows Media Player control is added to your toolbox.
Step 3
Now deign the form as you need to for the control. Here I use a TableLayout panel control on the form and set these properties to "Columncount =1, Dock =Fill and Rows=3". Now I have inserted the Windows Media Player control from the toolbox in the first row of the TableLayout panel and set the property "Dock=Fill". A list box and button control in the second and third row of the table layout panel with "Dock =Fill" property. And a OpenFileDialog to select one or more .mp3 files to play with the property.
Note: Now your windows look like this:
Step 4
Now write the following C# code in the "Form1.cs" page:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace media_player
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] files, path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() ==System.Windows .Forms .DialogResult .OK)
{
files = openFileDialog1.SafeFileNames;
path = openFileDialog1.FileNames;
for (int i = 0; i< files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
}
}
}
Step 5
Run your program.