Search code examples
c#visual-studio-2015wmplib

How to stop playing an mp3 when a button is pressed?


I just "moved" from C++ and a Rad Studio to C# and a Visual Studio as i can see more tutorials and help is available on the internet for VC. But.. I have a problem.

I know how to play a music when a form is created (when program starts). But how can i stop music playing using a normal TButton?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _01_21_2019
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            // play an intro sound when a form is shown
              WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
              wplayer.URL = "intro.mp3";
              wplayer.controls.play();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            wplayer.controls.stop(); // Here it is not working - "current context"



        }
    }
}

Compiler says

Error CS0103 The name 'wplayer' does not exist in the current context"

I tried to move wplayer.controls.stop() just below the play(); and it works. But how to stop music using a button?

Here is the code on pastebin:

https://pastebin.com/v9wDn5mJ


Solution

  • You should instantiate the object outside of the function so it's available for the class instance.

    You might also want to look into the mvvm pattern. It's very helpfull when writing WPF and some other applications.

    public partial class Form1 : Form
    {
        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Shown(object sender, EventArgs e)
        {
            // play an intro sound when a form is shown    
            wplayer.URL = "intro.mp3";
            wplayer.controls.play();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            wplayer.controls.stop();
        }
    }