Search code examples
c#naudio

playing and stopping audio from two different buttons


I'm running this code for pausing the song but it obliviously doesn't work. I can't access the variables of the first button from the second one, so I can't pause the song. How do you think I could do that? I'm using the naudio library cause I wanted to put the audio file as resource.

private void button3_Click(object sender, EventArgs e)
{            
    MemoryStream mp3file = new MemoryStream(Properties.Resources.musica1);                
    Mp3FileReader mp3reader = new Mp3FileReader(mp3file);
    var waveOut = new WaveOut();
    waveOut.Init(mp3reader);
    waveOut.Play();

            if (pausa)
            {
                waveOut.Pause();
            }


    }
    private void button2_Click(object sender, EventArgs e)
    {
        pausa = true;
    }

Solution

  • You will need to restructure your code. The problem is that in your button3_Click method, you are loading and playing your MP3, but then the function immediately terminates. The if statement won't be continuously checked, which is what I think you assume will happen. Therefore, clicking button2 will simply change the state of pausa but this doesn't affect anything.

    One way would be to make all the variables (mp3file, mp3reader, and waveOut) declared at the class level, then put the rest of the code inside button3_Click into, say, your form's Load event handler.

    // These variables are declared at the class level
    MemoryStream mp3file;
    Mp3FileReader mp3reader;
    WaveOut waveOut;
    
    ...
    
    private void Form1_Load(object sender, EventArgs e)
    {
        mp3file = new MemoryStream(Properties.Resources.musica1);                
        mp3reader = new Mp3FileReader(mp3file);
        waveOut = new WaveOut();
        waveOut.Init(mp3reader);    
    }
    

    Now, your buttonX_Click functions can look like this (assuming button3 is your Play button and button2 is your Pause button):

    private void button3_Click(object sender, EventArgs e)
    {
        waveOut.Play();
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        waveOut.Pause();
    }
    

    Because waveOut is declared at the class level, both buttons have access to it, and can therefore play and pause at will. You don't need pausa anymore, unless of course you need to know the playing state elsewhere in the program.