C # does not provide a class of audio files such as MP3, to write an audio file program such as playing MP3, you must use a third-party control or class. This article uses the API function McISendString to write a class that plays an audio file such as MP3. The specific source code is as follows: 1. The media play class consisting of API functions McISendstring. Using system.runtime.interopservices; using system.ipe;
Summary description of Namespace Clsmcil {///
// definition of API functions string variables [MarshalAs (UnmanagedType.ByValTStr, SizeConst = 260)] private string Name = ""; [MarshalAs (UnmanagedType.ByValTStr, SizeConst = 128)] private string durLength = ""; [MarshalAs (Unmanagedtype.lptstr, sizeconst = 128)] private string temstr = ""; int il; // Define play status enumeration variable public enum state {mplaying = 1, MPUASE = 2, MStop = 3}; // Structural Variable PUBLIC Struct structmci {public bool bmut; public int ipos; public int ip ibal; public string iname; public state stat;
Public structmci mc = new structmci (); // acquire play file attribute public string filename {get {return mc.iname;}
Set {// asciiencoding asc = new asciiencoding (); try {temstr = ""; temstr = Temstr.padleft (127, convert.tochar (")); name = name.padleft (260, control.tochar (" " )); Mc.iname = value; ilong = apiclass.getshstpathname (mc.iname, name, name.Length); name = getCurrPath (name); // name = "open" convert.tochar (34) Name Convert.TOCHAR (34) "alias Media"; name = "open" convert.tochar (34) Name Convert.ToChar (34) "Alias Media"; ilong = APICLASS.MCISENDSTRING ("Close All", TemStr, TemStr.Length, 0); ilong = APIClass.mciSendString (Name, TemStr, TemStr.Length, 0); ilong = APIClass.mciSendString ( "set media time format milliseconds", TemStr, TemStr.Length, 0); mc .State = state.mstop;} catch {messagebox.show ("Error Error!");}}} // Play Public Void Play () {Temstr = ""; Temstr = Temstr.padleft (127, Convert.ToCha) "")); APICLASS.MCISENDSTRING ("Play Media", Temst, Temstr.Length, 0); mc.state = S Tate.mplaying;} // Stop public void stopt () {temstr = ""; Temstr = Temstr.Padleft (128, Convert.ToChar (")); ilong = apiclass.mcisendstring (" Close Media ", Temst, 128 , 0); Ilong = APICLASS.MCISENDSTRING ("Close All", Temstr, 128, 0); mc.State = state.mstop;
Public void puase () {temstr = ""; temstr = Temstr.padleft (128, convert.tochar (")); ilong = apiclass.mcisendstring (" Pause Media ", Temstr, Temstr.length, 0); MC. State = state.mpuase;} private string getCurrPath (String name) {if (name.length <1) return "; name = name.trim (); name = name.substring (0, name.length-1); Return name;} // Total time public int duration {get {durlength = "; durlength = durlength.padleft (128, convert.tochar (")); APICLASS.MCISENDSTRING ("Status Media Length", Durlength, Durlength. Length, 0); durlength = DURLENGTH.TRIM (); if (durlength == ") RETURN 0; convert.todouble (durlength) / 1000f);}} // Current time public int currentposition {Get {Durlength = ""; durlength = durlength.padleft (128, convert.tochar (")); APICLASS.MCISENDSTRING (" status media position ", durlength, durlength.length, 0); mc.ipos = (int) ( Convert.TODOUBLE (DURLENGTH) / 1000F); return mc.ipos;}}}
Public class apiclass {[DLLIMPORT ("kernel32.dll", charset = charset.auto)] public static extern int GETSHORTPATHNAME (String Shortfile, int cchbuffer);
[DllImport ( "winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)] public static extern int mciSendString (string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
}
} Second, the code is a simple test for the media player classes: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; Using System.Text; Using System.io; Using ClsmCIPlay; Namespace McIPlay {///
// // Todo: Add any constructor code after INITIALIZEComponent call //}
///
#REGION Windows Form Designer The code ///
/// summary> private void InitializeComponent () {this.components = new System.ComponentModel.Container (); this.Play = new System.Windows.Forms.Button (); this.PlayFileName = new System.Windows. Forms.Label (); this.duration = new system.windows.forms.label (); this.stop = new system.windows.Forms.Button (); this.puase = new system.windows.Forms.Button () ; this.CurrentPosition = new System.Windows.Forms.Label (); this.timer1 = new System.Windows.Forms.Timer (this.components); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog (); this .Browserfile = new system.windows.Forms.Button (); this.suspendlayout (); // // play // this.play.location = new system.drawing.point (102, 243); this.play.name = "Play"; this.play.size = new system.drawing.size (78, 24); this.play.tabindex = 0; this.Play.Text = "THIS.PLAY.Click = new system . Eventhandler (this.play_click); // // playfilename // this.playFilename.autosize = true; this.playFilen Ame.Location = new system.drawing.point (12, 15); this.playFilename.Name = "playfilename"; this.playFilename.size = new system.drawing.size (0, 17); this.playFilename.tabindex = 1; // // duration // this.duration.autosize = true; this.duration.location = new system.drawing.point (15, 51); this.duration.name = "duration"; this.duration.size = new system.drawing.size (0, 17); this.duration.tabindex = 2; // // stop // this.stop.Location = new system.drawing.point (282, 243); this.stop. Name = "stop"; this.stop.size =
New system.drawing.size (81, 24); this.stop.Tabindex = 3; this.stop.Text = "stop"; this.stop.click = new system.EventHandler (this.stop_click); // / / Puase // this.puase.location = new system.drawing.point (198, 243); this.puase.name = "puase"; this.puase.size = new system.drawing.size (72, 24); This.puase.tabindex = 4; this.puase.text = "puase"; this.puase.click = new system.eventhandler (this.puase_click); /// CurrentPosition // this.currentPosition.autosize = true; This.currentPosition.location = new system.drawing.point (15, 87); this.currentPosition.name = "currentPosition"; this.currentPosition.size = new system.drawing.size (0, 17); this.currentPosition. TabINDEX = 5; // // Timer1 // this.timer1.enabled = true; this.timer1.interval = 1000; this.timer1.tick = new system.eventhandler (this.timer1_thing); // // BrowserFile / / This.browserfile.location = new system.drawing.point (312, 165); this.browserfile.name = "brow serFile "; this.BrowserFile.Size = new System.Drawing.Size (87, 24); this.BrowserFile.TabIndex = 6; this.BrowserFile.Text =" SelectFile "; this.BrowserFile.Click = new System.EventHandler (this.browserfile_click); // // form1 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (433, 287); this.controls.add (this.browserfile; this.currentPosition; this.controls.add (this.puase); this.controls.add (this.stop); this.Controls.add (this.duration); This.Controls.add (this.PlayFileName);
This.Controls.add (this.play); this.name = "form1"; this.text = "form1"; this.ResumeLayout (false);} #ENDREGION
///
// Select MP3 file Play Private Void Play_Click (Object Sender, System.EventArgs E) {mp.play ();} catch {messagebox.show ("Error Error!");}} // Pause Play Private Void PUase_Click (Object sender, system.eventargs e) {try {mp.puase ();} catch {messagebox.show ("Error Error!");
}
// Stop playing Private Void Stop_Click (Object Sender, System.EventArgs E) {Try {mp.stopt ();} catch {messagebox.show ("Error Error!");}} // Display once a play schedule private void timer1_Tick (object sender, System.EventArgs e) {CurrentPosition.Text = mp.CurrentPosition.ToString ();} // browse files private void BrowserFile_Click (object sender, System.EventArgs e) {try {openFileDialog1.Filter = "* .mp3 | * .mp3 "; openFileDialog1.FileName =" "; if (openFileDialog1.ShowDialog () == DialogResult.OK) {mp.FileName = openFileDialog1.FileName; PlayFileName.Text = openFileDialog1.FileName; Duration.Text = mp .Duration.toString ();}} catch {messagebox.show ("Error Error!");}}
}
} This program is compiled by .NET 2003, WIN XP SP1.