-1

I have seen a few posts about multi-function buttons here and elsewhere, but I am having trouble implementing their suggestions.

I am coding a synthesizer that generates and saves a .wav file. I have a button that plays the sound with SoundPlayer 'without saving it' by saving it to 'bin', and I delete it later. I realise this isn't an ideal way of playing sounds!

I've got the button label changing from "Play" to "Stop" when it is clicked. Unfortunately, I can't get the button to function as 'stop'.

I have tried creating a 'counter',

    public static int NumOfClicks = 0;

and doing NumOfClicks++ each time the button is clicked, then if(IsEven(NumOfClicks)), but it gives the error 'IsEven does not exist in this context'.

    private void btnPlay_Click_1(object sender, EventArgs e)
    {
        NumOfClicks++;                                      
        btnPlay.Text = "Stop";
           filePath = @"TestTone.wav";
           WaveGenerator wave = new WaveGenerator();
           wave.Save(filePath);
           SoundPlayer player = new SoundPlayer(filePath);
           player.Play();

         if (IsEven(NumOfClicks))
          {
                   btnPlay.Text = "Play";
                   player.Stop();
                   filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                   File.Delete(@"TestTone.wav");
          }


        }

I tried creating a separate 'stop' button, but then the player.Stop() command doesn't work (player 'does not exist in this context').

I tried using a switch with NumOfClicks but got the same 'player does not exist in this context' error.

If anyone has a fix or a better way of doing this I would greatly appreciate it!

1 Answers1

1

One way to solve this is to use two buttons. For initial development, have them both visible in different spots until the start/stop functionality works the way you need them to.

Once that is fixed, you can stack the two buttons and set the Visibility flag on them to set which one is shown, and which one is hidden.

// WPF Sample Code
void buttonPlay_onClick()
{
   // Do something
   buttonPlay.Visible = Visibility.Visible;
   buttonStop.Visible = Visibility.Hidden;
}

void buttonStop_onClick()
{
   // Do something
   buttonPlay.Visible = Visibility.Visible;
   buttonStop.Visible = Visibility.Hidden;
}

If you are using WinForms instead of WPF, your visibility switch will use these commands instead.

   buttonPlay.Visible = true;
   buttonStop.Visible = false;

By using two buttons, you can control the state of when each one can be clicked, and thereby simplify the code to handle the click rather than trying to track the number of clicks or similar. If the button is visible/active, the user can click it and execute the action.

Martin Noreke
  • 3,486
  • 16
  • 34