如何解决C#中的variable not in context错误?

How to solve variable not in context error in C#?

我希望在按下按键时播放声音,在松开按键时停止播放。

但我不知道如何停止 KeyUp 语句中的声音,因为它说 p46 不在上下文中。我读到变量不可能做到这一点,但这是真的吗?我可以在这里使用哪种方法使它起作用?

我也想让它同时播放2个声音

void Test_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.OemPeriod)
    {
        var p46 = new System.Windows.Media.MediaPlayer();
        p46.Open(new System.Uri(@"C:\Users\Shawn\Desktop\Sonstiges\LaunchBoard\LaunchBoard\bin\Debug\Sounds\Song1Audio41.wav"));
        p46.Volume = TrackWave.Value / 10.00;
        p46.Play();
        System.Threading.Thread.Sleep(50);
        button19.BackColor = Color.Red;
    }
}

void Test_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.OemPeriod)
    {
        button19.BackColor = SystemColors.Control;
        button19.UseVisualStyleBackColor = true;
    }
}

doctorlove(上面的评论)是对的。您需要使用两种不同方法的 MediaPlayer,而不是两种 class。所以只需将它移动到 class-scope 即可。也就是所谓的(私有)字段.

看起来像这样:

using System;
using System.Threading;
using System.Windows.Media;

namespace Xx
{
  class Yy
  {
    MediaPlayer p46 = new MediaPlayer(); // field (class-level variable), 'var' not allowed

    void Test_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.OemPeriod)
      {
        // can see p46 here:
        p46.Open(new Uri(@"C:\Users\Shawn\Desktop\Sonstiges\LaunchBoard\LaunchBoard\bin\Debug\Sounds\Song1Audio41.wav"));
        p46.Volume = TrackWave.Value / 10.00;
        p46.Play();
        Thread.Sleep(50);
        button19.BackColor = Color.Red;
      }
    }

    void Test_KeyUp(object sender, KeyEventArgs e)
    {
      // can see p46 here:
    }
  }
}