Search code examples
c#asp.netvisual-studiowinformswindows-media-player

2 songs playing at the same time


I have a project I'm working on. music playing platform. i use windows media player for this but i have a problem. The music comes as a list from the database. There is a play button at the top of the lists. When I press the button, the music plays smoothly. but when I play another song, the other music doesn't stop and they both play at the same time. I need your help. I think the problem is caused by the following codes

private bool durum = false;
    
    public void btn_koynat_Click(object sender, EventArgs e)
    {
        
        Form1 frm1 = (Form1)this.FindForm();
        frm1.player = player;

       
        if (durum == true)
        {
            durum = false;
            
            frm1.sarkislider.Value = 0;
        }
        if (durum==false)
        {
            durum = true;
            int sec = Convert.ToInt32(label_sec.Text);
            frm1.btn_Oynat.Enabled = true;
            frm1.durum = true;
            player.URL = label_sarki.Text + ".MP3";
            
            
            btn_koynat.BackgroundImage = Properties.Resources.sesacik;
            frm1.btn_Oynat.BackgroundImage = Properties.Resources.durdurbutonu;
            frm1.sarki_isim.Text = label_sarki.Text;
            frm1.sarki_sanatci.Text = label_sanatci.Text;
            frm1.label_timer2.Text = label3.Text;
            frm1.sarkislider.Maximum = sec;
            frm1.timer1.Enabled = true;
            frm1.sarkislider.Value = 0;




            player.controls.play();
        }
    }

Solution

  • You can use wplayer.playState to check if your player is running.

    Here is a code example, which can avoid playing two songs at the same time.

     WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
            private void button1_Click(object sender, EventArgs e)
            {
                if (wplayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
                {
                    wplayer.controls.stop();
                    wplayer.URL = comboBox1.SelectedItem.ToString();
                    wplayer.controls.play();
                }
                else
                {
                    wplayer.URL = comboBox1.SelectedItem.ToString();
                    wplayer.controls.play();
                }
         
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                comboBox1.Items.Add("1.mp3");
                comboBox1.Items.Add("2.mp3");
                comboBox1.Items.Add("3.mp3");
                comboBox1.Items.Add("4.mp3");
                comboBox1.Items.Add("5.mp3");
    
            }
    

    Note: I used combobox to store mp3 files. Based on my test, when I play a mp3 file and click button to play another mp3 file, the initial mp3 file was stopped and play another file.