Play MP3


We can play the MP3 songs using the following class.

We have two classes. The first one will show you the logic of playing
the MP3 songs. Second class will show you how to use the first class.

Following are the name spaces used


using System;
using System.Runtime.InteropServices;


Following is the PlaySongs Class. The winmm.dll is used to paly the songs.
Following code will explain clearly. How to play the songs.


class PlaySongs
{

private string _command;
private bool isOpen;

[DllImport("winmm.dll")]

private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);

public void Close()
{

_command = "close MediaFile";

mciSendString(_command, null, 0, IntPtr.Zero);

isOpen = false;
}

public void Open(string sFileName)
{
_command = "open \"" sFileName "\" type mpegvideo alias MediaFile";
mciSendString(_command, null, 0, IntPtr.Zero);
isOpen = true;
}
public void Play(bool loop)
{
if(isOpen)
{
_command = "play MediaFile";
if (loop)
_command = " REPEAT";
mciSendString(_command, null, 0, IntPtr.Zero);
}
}
}




This is the UI. We can play the songs using this UI.

Name space part

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;


The following is the coding part of the UI of the player

public partial class MyPlayer : Form
{
PlaySongs PlayMySongs = new PlaySongs();
public String MyCurrentSong = "";
public MyPlayer()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Mp3 (*.mp3)|*.mp3";
}

private void button1_Click(object sender, EventArgs e)
{
if (CurrentSong != "")
{
PlayMySongs.Close();
PlayMySongs.Open(MyCurrentSong);
PlayMySongs.Play(true);
}
}

private void button2_Click(object sender, EventArgs e)
{
PlayMySongs.Close();
}

private void button3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CurrentSong = openFileDialog1.FileName.ToString();
}
}
}




By
Nathan


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: