Play Music with MCI interface

Source: Internet
Author: User

There are three main ways of playing music in C #: 1, system.media.soundplay;2, MCI interface, 3, MediaPlayer control. Soundplay is specifically used to play sound, that is,. wav files, the use of the method is relatively simple. The MediaPlayer control is the system's own player, and it's been introduced a lot.

Today I would like to introduce you to the MCI interface, about the MCI interface, you can refer to MSDN, here we just introduce specific usage. First, we need to define an enumeration type to describe the state of the player.

  Public enum Playstate:byte
    {
        Playing = 1,
        puased = 2,
        Stopped = 3,
    }


Next, to facilitate subsequent continuation, we have encapsulated the MCI interface:

  Class WAPI
    {
        [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] public
        static extern int GetShortPathName (
        string Lpszlongpath,
        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
        );
    

For these two API functions, you can find instructions on MSDN. Next, we'll build the class for the player:

 public class MPlayer {//define song address private string Url = String.
        Empty;
        Define an instance of the song structure private Media m = new Media ();
            Constructor public MPlayer () {m.position = 0;
            M.state = playstate.stopped;
            M.volume = 0;
            M.speed = 1000;
        m.duration = 0; //filename Property public string FileName {set {URL = Stri Ng.
                Empty;
                string Name = value;
                m.position = 0;
                URL = Url.padleft (260, ' "); Wapi.
                GetShortPathName (Name, URL, url.length);
                url = getfileurl (URL);
            Initdevice (); }//Device initialization private void Initdevice () {String DeviceID = Getdeviceid (URL);
            return type wapi.mcisendstring ("Close all", NULL, 0, 0);//Turn off all devices if (DeviceID!= "Realplay")
        {        String mcicommand = String.Format ("Open {0} type {1} Alias Media", URL, DeviceID);
            Wapi.mcisendstring (Mcicommand, NULL, 0, 0);//Initialize device m.state = playstate.stopped; }//Get device ID private string Getdeviceid (String Url) {string result = string.
            Empty; URL = Url.toupper ().
            Trim ();
            if (Url.length < 3) {return Url; Switch (url.substring (url.length-3)) {case ' MID ': Result
                    = "Sequencer";
                Break
                    Case "RMI": result = "sequencer";
                Break
                    Case "IDI": result = "sequencer";
                Break
                    Case "WAV": result = "Waveaudio";
                Break
 Case "ASX": result = "MPEGVideo2";                   Break
                    Case "IVF": result = "MPEGVideo2";
                Break
                    Case "LSF": result = "MPEGVideo2";
                Break
                    Case "LSX": result = "MPEGVideo2";
                Break
                    Case "P2V": result = "MPEGVideo2";
                Break
                    Case "WAX": result = "MPEGVideo2";
                Break
                    Case "WVX": result = "MPEGVideo2";
                Break Case. "
                    WM ": result =" MPEGVideo2 ";
                Break
                    Case "WMX": result = "MPEGVideo2";
                Break
                    Case "WMP": result = "MPEGVideo2";
                Break
                    Case ". RM": result = "Realplay"; BreAk
                    Case "RAM": result = "Realplay";
                Break Case. "
                    RA ": result =" Realplay ";
                Break
                    Case "MVB": result = "Realplay";
                Break
                    Default:result = "MPEGVideo";
            Break
        return result; //Get current path private string Getfileurl (string filename) {filename = Filename.trim ();/ Remove the space if (Filename.length > 1)//Determine if it is empty (name contains ' ") {FileName = Filename.substri
        Ng (0, filename.length-1);//Remove ' ""} return FileName;
            //Determine if the device is ready to accept the command after initialization public bool IsReady () {String Ready = new String (', 10);
            Wapi.mcisendstring ("Status Media Ready", Ready, Ready.length, 0);
   Ready = Ready.trim ();         if (Ready.contains ("true")) {return true;
            else {return false;
            Playing public void play () {if (m.state!= playstate.playing)
                {wapi.mcisendstring ("play Media", NULL, 0, 0);
            M.state = playstate.playing;
            Stop public void Stop () {if (M.state!= playstate.stopped)}//
                {wapi.mcisendstring ("Stop Media", NULL, 0, 0);
            M.state = playstate.stopped;
            }//Pause public void Puase () {if (m.state = = playstate.playing)
                {wapi.mcisendstring ("Pause Media", NULL, 0, 0);
            M.state = playstate.puased; }//Restore play public void Resume () {int refint = Wapi.mcisendString ("Resume Media", NULL, 0, 0);
        M.state = playstate.playing; }//property Duration public int Duration {get {WAPI.MCISENDST
                Ring ("Set Media time format milliseconds", NULL, 0, 0);//Set times format unit to milliseconds m.duration = Getduration ();
            return m.duration; The private int getduration () {string Length = string.
            Empty; Length = Length.padleft (20, ');/set fixed-length string long is 19-bit, enough to indicate time Wapi.mcisendstring ("Status Media Length", Length, L Ength.
            Length, 0);
            Length = Length.trim ();
                if (Length.length > 1) {Length = length.substring (0, length.length-1); return (int) (long.
            Parse (Length)/1000);
        return 0; }//Property state public Playstate state {get {return m.state
    ;        } public string Positionstring {get {string m m = (this. POSITION/60).
                ToString ("00"); string SS = (this. Position% 60).
                ToString ("00");
            return mm + ":" + SS; } public string Durationstring {get {a string mm = (thi S.DURATION/60).
                ToString ("00"); string SS = (this. Duration% 60).
                ToString ("00");
            return mm + ":" + SS;  }//Set gets current time public int Position {get {string Position = string.
                Empty; Position = Position.padleft ("");//long indicates a range of 19-bit wapi.mcisendstring ("Status Media Position", Position,
                Position.length, 0);
                Position = Position.trim (); if (Position.length > 1) {m.position = (int) (Long.
            Parse (Position)/1000);//returns in seconds} return m.position;
                The set {string Command = String.Format ("seek Media to {0}", value*1000);
                Wapi.mcisendstring (Command, NULL, 0, 0);//Make play stop m.state = playstate.stopped;
                M.position = value*1000;
            Play (); }//Set mute public void Volumeoff (bool isoff) {string setonoff = string.
            Empty;
            if (isoff) Setonoff = "Off";
            else Setonoff = "on";
            String mcicommand = String.Format ("Set Audio Media {0}", Setonoff);
        Wapi.mcisendstring (Mcicommand, NULL, 0, 0);
            //volume public int Volume {get {return m.volume;
         set {if (value >= 0) {           M.volume = value;
                    String mcicommand = String.Format ("Set Audio Media Volume to {0}", M.volume);
                Wapi.mcisendstring (Mcicommand, NULL, 0, 0);
            }}//define song structure private struct Media {public int Position;
            Public Playstate State;
            public int Volume;
            public int Speed;
        public int Duration; }
    }

About this class, I want to say two, first: when setting the Position property, the song's progress, we assign the value to value*1000. Why multiply by 1000? Because when we get position, we do a unit conversion, except for 1000, so multiply this by 1000, otherwise the program won't work. Second: Use MCI when playing, often hissing murmur, my solution is to set the song before playing 1 seconds, that is, the song does not start from the beginning, so you can jump past, hehe. All right, that's it, let's go to sleep.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.