C# music player is based on C# form program design and development, is to learn C#winform development of a good actual combat project. This paper explains the basic control of music player function writing and development ideas

Function directory

  • Open the music file control function
  • Double-click the music to trigger the play property function
  • Play or pause control property functions
  • Stop the control property function
  • Click the next control function
  • Click the next control function
  • Music deletion function
  • Click mute function
  • Time monitoring control function
  • Determine if there is a function in the lyrics
  • Lyric formatting function
  • Play lyrics function



Recently in the study of C# GUI programming thought to make a player, said to do.

In fact, C# has significant advantages in game development, in winform interactive page design and web site development is also unique.

So for using C# to develop a music player, the first thing we should understand is of course the basic composition of the player, after all, know yourself and know your opponent can win a hundred battles, and we usually use the same music player.

Of course, the player we make should also have the ability to add, delete, multiselect, mute, pause, stop, switch,

At the same time, in order to be more consistent with the use of common players, we also need to add automatic switching to the next song, real-time time display, player screen and other basic operations.



.

Now when we know what functions our player needs to realize, it is the stage for us to build the interface and function methods of the whole player. In the design interface of VS software, we can easily carry out the overall layout of the interface of the player.

At the same time we add each control has its unique attributes, we can control the attributes of personalized Settings, increase our better experience.

The following is the player interface built by the big Bad Wolf, which can be referred to by friends. The basic interface and required functions of the player are realized.

After the interface design is complete, it’s time to write back end functions,

Open the music file control function

The purpose of this function is to add music files from system files.

The basic idea is: first define a list of paths to store each piece of music, and then after selecting the music file, add the path of the selected music file to the path list. It needs to be noted that we need to set the default opening position of the music and the selected music format. Generally, the music format includes MP3, WAV, FLAC, etc. When setting the music format in the property, it should be noted that each format should be separated by a semicolon.

Function implementation code is as follows:

// Define a list file path
        List<string> listpath = new List<string> ();// Set the open music file property
        private void openmusic_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            // Set the default starting position for music
            ofd.InitialDirectory = @"‪C:/Users/ Guo Yungang /Music";

            // Set the music format that can be matched
            ofd.Filter = "MP3 file | *. MP3; *.wav";
            //ofd.Filter = null;

            // Set the name of the title box above
            ofd.Title = "Please select the music file!";

            // Set to allow multiple selections
            ofd.Multiselect = true;
            ofd.ShowDialog();

            // Get the full path to the selected file
            string[] path = ofd.FileNames;

            for (int i = 0; i < path.Length; i++)
            {
                // Add the full path to the music file to the list
                listpath.Add(path[i]);

                // Add the music file name to the listlistBox1.Items.Add(Path.GetFileName(path[i])); }}Copy the code

.

Double-click the music to trigger the play property function

After adding the music, of course we need to play the music, in this case we need to set it to play in the MusicPlayer when we double click the music file.

The important thing about this function is that we need to determine the list of music files, and if the list is zero, that is, there is no music available to play, we need to inform the user. Also, after we double click to play the music, the control we set to play the music should now display the pause option.

The implementation code is as follows:

// Double-click the music to trigger the play property
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (listBox1.Items.Count == 0)
            {
                MessageBox.Show("Please select play music first!");
                return;
            }
            try
            {
                musicPlayer.URL = listpath[listBox1.SelectedIndex];
                musicPlayer.Ctlcontrols.play();
                playorpause.Text = "Pause";
                //timer1_Tick_1(sender, e);
                //music_plan.Text = musicPlayer.currentMedia.duration.ToString();
                
                // Call the function to process the lyrics of the song in this path
                IsExistlrc(listpath[listBox1.SelectedIndex]);
            }
            catch
            { }
            
        }
Copy the code

Play or pause control property functions

The function of this control, as the name suggests, is of course to control the play and pause of the music, and it is important to note that when we click on the music to play, we should let the music continue, not restart. The control should also be displayed after we click the play or pause button.

The implementation code is as follows:

// Set the play or pause button properties
    private void playorpause_Click(object sender, EventArgs e)
    {
        if (playorpause.Text == "Play")
        {

            // Raise an exception to prevent the list from having no music
            try
            {
                // If you continue to click play, let him continue to play
                if (b)
                {
                    musicPlayer.URL = listpath[listBox1.SelectedIndex];

                }
            }
            catch
            { }
            musicPlayer.Ctlcontrols.play();
            playorpause.Text = "Pause";
        }
        else if (playorpause.Text == "Pause")
        {
            musicPlayer.Ctlcontrols.pause();
            playorpause.Text = "Play";
            b = false; }}Copy the code

Stop the control property function

When the user clicks Stop, the currently playing music stops and returns to its original position.

The implementation code is as follows:

 // Sets the stop control property
        private void button3_Click(object sender, EventArgs e)
        {
            musicPlayer.Ctlcontrols.stop();
            playorpause.Text = "Play";
        }
Copy the code

.

Click the next control function

When we click next, we can play the next song in the current music list.

The implementation code is as follows:

// Click next
        private void music_down_Click(object sender, EventArgs e)
        {
            // Get the current song index position
            int index = listBox1.SelectedIndex;

            // Clear the song selection index
            listBox1.SelectedIndices.Clear();

            index++;
            if (index == listBox1.Items.Count)
            {
                index = 0;
            }
            listBox1.SelectedIndex = index;
            musicPlayer.URL = listpath[index];
            musicPlayer.Ctlcontrols.play();
        }
Copy the code

Click the next control function

This function plays the last song in the current playlist when you click on the previous song.

The implementation code is as follows:

 // Click on the previous song
        private void music_up_Click(object sender, EventArgs e)
        {
            int index = listBox1.SelectedIndex;
            

            listBox1.SelectedIndices.Clear();
            index--;

            // If this is the first song, the index is reduced by 1 to -1
            if (index == - 1)
            {
                // listbox1.items. Count records the number of songs,
                // If you jump to the last track, the index is the number minus one
                index = listBox1.Items.Count - 1;
            }

            listBox1.SelectedIndex = index;

            musicPlayer.URL = listpath[index];
            musicPlayer.Ctlcontrols.play();
        }
Copy the code

Music deletion function

This function is used to delete music that has been stored in the music list. When we click to select a music, we can delete it from the list. And it won’t play the music on auto play.

The implementation code is as follows:

 // Click Delete
        private voidDelete ToolStripMenuItem_Click (object sender, EventArgs e)
        {
            // Get the number of selected songs
            int count = listBox1.SelectedItems.Count;

            // Remove the selected item from the list
            for (int i = 0; i < count; i++)
            {
                // First delete the songs in the collection
                listpath.RemoveAt(listBox1.SelectedIndex);
                // Delete the songs stored in the listlistBox1.Items.RemoveAt(listBox1.SelectedIndex); }}Copy the code

Click mute function

Mute the mute function is used to mute the music after the mute is clicked, but the music can still be played. This function is related to settings.mute.

This function is implemented as follows: we need to set whether the current music is muted. Because the Text of the Text mute control is always unchanged, we need to use the Tag attribute of the control to determine whether the music is muted.

The specific implementation code is as follows:

 // Click mute function
        private void label1_Click(object sender, EventArgs e)
        {
            if (label1.Tag.ToString() == "1")
            {
                musicPlayer.settings.mute = true;
                
                // label1.image = image.fromfile (@"‪C:/Users/ Pictures/320578.png"); // label1.image = image.fromfile (@"‪C:/Users/ Pictures/320578.png");
                label1.Tag = "2";
            }
            else if (label1.Tag.ToString() == "2")
            {
                musicPlayer.settings.mute = false;
                // label1.image = image.fromfile (@"C:/Users/ Pictures/322557.png");
                label1.Tag = "1"; }}Copy the code

Time monitoring control function

This function requires us to bind with the time monitoring control after adding the time control. The function is to monitor the playing music in real time and return the current playing time.

The specific implementation code is as follows:

// Time control 1
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            //music_plan.Text = "test ";
            // If the player state is playing
            if (musicPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
            {
                //music_plan.Text = "play ";
                music_plan.Text = musicPlayer.currentMedia.duration.ToString() + "\r\n" + musicPlayer.currentMedia.durationString + "\r\n" + musicPlayer.Ctlcontrols.currentPosition.ToString() + "\r\n" + musicPlayer.Ctlcontrols.currentPositionString;

                double t1 = double.Parse(musicPlayer.currentMedia.duration.ToString());
                double t2 = double.Parse(musicPlayer.Ctlcontrols.currentPosition.ToString()) + 1;
                if ( t1 <= t2)
                {
                    // Get the current song index position
                    int index = listBox1.SelectedIndex;

                    // Clear the song selection index
                    listBox1.SelectedIndices.Clear();

                    index++;
                    if (index == listBox1.Items.Count)
                    {
                        index = 0; } listBox1.SelectedIndex = index; musicPlayer.URL = listpath[index]; musicPlayer.Ctlcontrols.play(); }}}Copy the code

Determine if there is a function in the lyrics

Understanding friend may know music files, each song music lyrics and music files were independent of each other, usually is a music file filename. Add after LRC England for its corresponding lyrics file, so when we play a song, you need our judgment on the lyrics of the song files, judge whether the current playing music with lyrics file.

If there is, lyrics standardization and lyrics playing functions will be carried out. If not, of course, users need to be prompted “lyrics not found”.

The implementation code is as follows:

// Check if the lyrics exist
        void IsExistlrc(string songPath)
        {
            // Clear the list of lyrics and dates before you make them
            listlrcTime.Clear();
            listlrcText.Clear();

            songPath += ".lrc";
            //MessageBox.Show(songPath);
            bool fileIn = File.Exists(songPath);
            if (fileIn)
            {
                //label_lyric.Text = "About to play lyrics ";
                // Define a list of lyrics to store the contents of the lyrics file
                string[] lrcText = File.ReadAllLines(songPath, Encoding.Default);

                // If the lyrics exist, formatlrc is called to format the lyrics
                formatlrc(lrcText);
            }
            else
            {
                label_lyric.Text = "Lyrics not found......"; }}Copy the code

Lyric formatting function

Many friends may not know that the original lyrics are specially processed, the real lyrics file is not only lyrics, it also includes the time each line should play.

As follows:

Therefore, when we display lyrics, we need to specialize the lyrics file, so that only lyrics are really displayed. Here, we need to separate each line of lyrics file, and store the obtained playing time and lyrics respectively in the corresponding list summary.

The specific implementation code is as follows:

       // Define a list of times to store lyrics
        List<double> listlrcTime = new List<double> ();// Define a list of lyrics to store
        List<string> listlrcText = new List<string> ();// Define a list of times to store lyrics
        List<double> listlrcTime = new List<double> ();// Define a list of lyrics to store
        List<string> listlrcText = new List<string> ();// Standard formatting function for lyrics
        void formatlrc(string [] lrcText)
        {
            for (int i = 0; i < lrcText.Length; i++)
            {
                // Remove the [,] before and after each line of the lyrics
                string[] lrcTemp = lrcText[i].Split(new char[] { '['.'] '}, StringSplitOptions.RemoveEmptyEntries);
                LrcTemp [0] is the time in the format of 00:00.00
                / / lrcTemp [1] is the lyrics

                // Remove the colon ":" from the time character.
                string [] lrcNewTemp= lrcTemp[0].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

                // Define the variable time to represent the time
                double time = double.Parse(lrcNewTemp[0]) * 60 + double.Parse(lrcNewTemp[1]);

                // Place each captured lyric time in the lRCTime list
                listlrcTime.Add(time);

                // messagebox.show (" testpoint 1");
                // Store the corresponding lyrics for each time in the generic list listlrcText
                listlrcText.Add(lrcTemp[1]);
            
            }
            // messagebox.show (" testpoint 1");
        }
Copy the code

Play lyrics function

Detected when we are going to play the song’s lyrics file exists, will the lyrics format file, and real-time broadcast out the words, then you need to define a time monitoring control and other lyrics to monitor the playing time, and may, according to the needs of real-time show time, play the lyrics.

The specific implementation code is as follows:

// Play the lyrics
        private void timer2_Tick(object sender, EventArgs e)
        {
            //label_lyric.Text = "About to play lyrics..." ;
            for (int i = 0; i < listlrcTime.Count; i++)
            {
                if (musicPlayer.Ctlcontrols.currentPosition >= listlrcTime[i] && musicPlayer.Ctlcontrols.currentPosition < listlrcTime[i + 1])
                {
                    // messagebox.show (" I want to play lyrics ");
                    // Display the lyrics of this period in the text box of the lyricslabel_lyric.Text = listlrcText[i]; }}}Copy the code

After each control function method is completed, the basic function of the music player is completed,

It is worth noting that when the lyrics are displayed, the lyrics of some music files will be interlinked with the space, resulting in the lyrics formatting function can not identify, it is recommended to modify the lyrics file suffix to TXT format, delete the space and then lyrics display processing.

I think so. Yeah.Thumb up attention!

At the same time, you can also follow my wechat official account.The Wolf hole Lord“Get more actual combat projects to share! The official account replied”Python notesGet getting started with Python to mastering Learning Notes and Quick Notes on common Python knowledge!

Big bad Wolf is looking forward to progress with you!