faiface / beep

A little package that brings sound to any Go application. Suitable for playback and audio-processing.
MIT License
2.03k stars 150 forks source link

Tutorial Code Freezes if Called Twice #157

Closed drgrib closed 1 year ago

drgrib commented 1 year ago

I am trying to create the simplest possible use of beep by creating a Play function that plays an MP3 using the tutorial code. I don't need any complex controllers or resampling. I just want to play the MP3. However when I call this code with a second MP3 (or the same MP3 a second time), the code freezes at the spot I have marked in the function.

How can I modify this code so that it doesn't freeze when called a second time?

func Play(p string) error {
    f, err := os.Open(p)
    if err != nil {
        return errors.WithStack(err)
    }

    streamer, format, err := mp3.Decode(f)
    if err != nil {
        return errors.WithStack(err)
    }
    defer streamer.Close()

    err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
    if err != nil {
        return errors.WithStack(err)
    }

    done := make(chan bool)
    // Second call freezes HERE
    speaker.Play(beep.Seq(streamer, beep.Callback(func() {
        done <- true
    })))

    <-done
    return nil
}
drgrib commented 1 year ago

I had to create a global variable in the package to not call speaker.Init. It would be nice to have an example of the best way to implement a simple play function in the example code.

Here was my workaround for anyone else stuck with this:

    if !initialized {
        err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
        if err != nil {
            return errors.WithStack(err)
        }
        initialized = true
    }
able8 commented 9 months ago

Thanks. I also encountered this issue. The second call to the speaker.Play() freezes.