WPF Music Player (i) Construction of music playback class---

Source: Internet
Author: User

Well, let's start with the first part of the tutorial--the construction of music playback classes.

There are several ways to play music in WPF: MediaPlayer class, SoundPlayer class, and using DirectX sound. To choose a more functional, easy-to-use approach, it's a MediaPlayer class, and the only limitation is that you need to rely on Windows Media Player (WMP). However, in the Windows environment, this limit can be ignored, is the system itself, is not it?

Of course, we can directly control the MediaPlayer operation code in the window, but for the sake of normalization and maintainability, we encapsulate it into the Musicplayer class.

At the beginning of the class, you define several private variables and public enumerations (representing the state of the player):

The code is as follows Copy Code

Public enum Playstate:int
       {
            stoped = 0,
           playing = 1,
           paused = 2
       }
       private MediaPlayer player = null;
        private Uri Musicfile;
       private playstate state;

Public Uri Musicfile
{
Set
{
Musicfile = value;
}
Get
{
return musicfile;
}
}

Next, write the constructor, one with parameters (the music file path), and one with no parameters:

The code is as follows Copy Code

Public Musicplay ()
{
Player = new MediaPlayer ();
}
Public Musicplay (Uri file)
{
Load (file);
The constructor function passes the incoming file path to the Load method, and the following is the code for the Load method:


public void Load (Uri file)
{
Player = new MediaPlayer ();
Musicfile = file;
Player. Open (Musicfile);

}

The Musicfile (public variable, indicating file path) is set in the Load method, and the music file is loaded with the MediaPlayer open method.

Next is the code to play, pause, and stop:

The code is as follows Copy Code
public void Play ()
{
Player. Play ();
state = playstate.playing;
}
public void Pause ()
{
Player. Pause ();
state = playstate.paused;
}
public void Stop ()
{
Player. Stop ();
state = playstate.stoped;
}

The first code of the above three methods is to set playback, pause, and stop, and the second code is to set the player's current state.

Then the natural duration of getting the music file:

The code is as follows Copy Code
Public TimeSpan Getmusicdurationtime ()
{
while (!player. Naturalduration.hastimespan)
{
if (player. Naturalduration.hastimespan)
{
Return player. Naturalduration.timespan;
}
}
return new TimeSpan ();
}

Here, a MediaPlayer naturalduration.hastimespan is used to check whether the natural duration of the music can be read, and a while loop is used to avoid reading to null values or reading.

This is the way to set and get the current progress:

The code is as follows Copy Code


public void SetPosition (TimeSpan tp)
{
Player. Position = TP;
}
Public TimeSpan GetPosition ()
{
Return player. Position;
Set the volume and read volume, and the incoming parameter is 0, which is muted:


public void SetVolume (double volume)
{
Player. Volume = Volume;
}
Public double Getvolume (double volume)
{
Return player. Volume;
}

Gets and sets the status of the current player, which is only three states, but may actually be more:

The code is as follows Copy Code

Public Playstate getplaystate ()
{
return state;
}
public void Setplaystate (playstate state)
{
if (state = = playstate.playing)
{
This. Play ();
}
else if (state = = playstate.paused)
{
This. Pause ();
}
else if (state = = playstate.stoped)
{
This. Stop ();
}
}

Add a way to get the music name based on the file path:

The code is as follows Copy Code
public string Getmusictitle ()
{
String Title=player. Source.tostring ();
return title. Substring (title. LastIndexOf ("/") +1, title. Length-title. LastIndexOf ("/")-1);
}

The second code of this method is to intercept the last "/" part of the string.

And I also defined a dispatchertimer here to update the location of the music, can complete the same task with change notification, but I did not use, we can try.

Here is the complete code, no comment, make it easy to see, should not be difficult:

  code is as follows copy code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
Namespace WpfApplication10
{
   public  class Musicplay
    {
 & nbsp;     public enum Playstate:int
       {
  & nbsp;        stoped = 0,
            playing = 1,
           paused = 2
       }
       private MediaPlayer player = null;
        private Uri Musicfile;
       private playstate state;

       public Uri musicfile
       {
            Set
            {
               musicfile = value;
          }
           Get
            {
                return musicfile;
          }
      }

      public DispatcherTimer dt = null;
       Public Musicplay ()
       {
            player = new MediaPlayer ();
      }
       public musicplay (Uri file)
       {
& nbsp;          Load (file);
          
           
      }

public void Load (Uri file)
{
Player = new MediaPlayer ();
Musicfile = file;
Player. Open (Musicfile);

}

public void Play ()
{
Player. Play ();
Dt. Start ();
state = playstate.playing;
}
public void Pause ()
{
Player. Pause ();
state = playstate.paused;
}
public void Stop ()
{
Player. Stop ();
state = playstate.stoped;
}
public string Getmusictitle ()
{
String Title=player. Source.tostring ();
return title. Substring (title. LastIndexOf ("/") +1, title. Length-title. LastIndexOf ("/")-1);
Return "";
}
Public TimeSpan Getmusicduringtime ()
{
while (!player. Naturalduration.hastimespan)
{
if (player. Naturalduration.hastimespan)
{
Return player. Naturalduration.timespan;
}
}
return new TimeSpan ();

}
public void SetPosition (TimeSpan tp)
{
Player. Position = TP;
}
Public TimeSpan GetPosition ()
{
Return player. Position;
}
public void SetVolume (double volume)
{
Player. Volume = Volume;
}
Public double Getvolume (double volume)
{
Return player. Volume;
}
Public Playstate getplaystate ()
{
return state;
}
public void Setplaystate (playstate state)
{
if (state = = playstate.playing)
{
This. Play ();
}
else if (state = = playstate.paused)
{
This. Pause ();
}
else if (state = = playstate.stoped)
{
This. Stop ();
}
}
}
}

Well, the code is all finished, we can refer to.

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.