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

129 Views Asked by At

I want that the sound plays if I press the key and stop if I release the key.

But I don't know how I could stop the sound in the KeyUp statement, because it says p46 isn't in the context. I read that this isn't possible with variables, but is it true? Which method can I use here to make it work?

I also want it to play 2 sounds at the same time.

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;
    }
}
1

There are 1 best solutions below

1
Jeppe Stig Nielsen On BEST ANSWER

doctorlove (comment above) is right. You need to use the MediaPlayer from two difference methods, not two classes. So just move it to the class-scope. That is what is called a (private) field.

It looks like this:

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:
    }
  }
}