如何在按下按钮时停止播放 mp3?

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

我只是 "moved" 从 C++ 和 Rad Studio 到 C# 和 Visual Studio,因为我可以在互联网上看到更多教程和帮助 VC。但是..我有一个问题。

我知道如何在创建表单时(程序启动时)播放音乐。但是我怎样才能停止使用普通的音乐播放 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"



        }
    }
}

编译器说

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

我试图将 wplayer.controls.stop() 移动到 play() 下方;它有效。但是如何使用按钮停止音乐?

这是 pastebin 上的代码:

https://pastebin.com/v9wDn5mJ

您应该在函数外部实例化对象,以便它可用于 class 实例。

您可能还想查看 mvvm 模式。在编写 WPF 和其他一些应用程序时非常有帮助。

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();
    }
}