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

Can I also stream the played sound to a file? #169

Open dhairya0904 opened 4 months ago

dhairya0904 commented 4 months ago

Hi

I have a use case where I want to play the sound and also stream this to file to play it again.

package main

import (
    "log"
    "os"
    "time"

    "github.com/faiface/beep"
    "github.com/faiface/beep/mp3"
    "github.com/faiface/beep/speaker"
)

func main() {

    s1 := getStream("./Lame_Drivers_-_01_-_Frozen_Egg.mp3")
    s2 := getStream("./Miami_Slice_-_04_-_Step_Into_Me.mp3")

    defer s1.Close()
    defer s2.Close()

    speaker.Init(48000, 2048)
    mixer := &beep.Mixer{}
    // done := make(chan bool)
    speaker.Play(mixer)

    mixer.Add(s1)
    mixer.Add(s2)

    time.Sleep(2 * time.Minute)
}

func getStream(file string) beep.StreamSeekCloser {
    f, err := os.Open(file)
    if err != nil {
        log.Fatal(err)
    }

    streamer, _, err := mp3.Decode(f)
    if err != nil {
        log.Fatal(err)
    }

    return streamer
}

I want this sound to be saved in a file, such that I can play the entire stream again. Can anyone please help me with this? Any help is appreciated

MarkKremer commented 3 months ago

Hi :wave: thank you for using Beep!

You can save audio to a file using the wav.Encode() function. Other encoding formats aren't supported currently.

Note that this repository is archived, but you can find our active fork over at https://github.com/gopxl/beep.

dhairya0904 commented 3 months ago

@MarkKremer I tried this but somehow the output file is too big.

package main

import (
    "log"
    "os"

    "github.com/faiface/beep"
    "github.com/faiface/beep/mp3"
    "github.com/faiface/beep/wav"
)

func main() {

    s1 := getStream("./Lame_Drivers_-_01_-_Frozen_Egg.mp3")
    s2 := getStream("./Miami_Slice_-_04_-_Step_Into_Me.mp3")

    defer s1.Close()
    defer s2.Close()

    mixer := &beep.Mixer{}
    mixer.Add(s1)
    mixer.Add(s2)

    outFile, err := os.Create("mixed_audio.wav")
    if err != nil {
        log.Fatal(err)
    }
    defer outFile.Close()

    err = wav.Encode(outFile, mixer, beep.Format{SampleRate: 48000, NumChannels: 2, Precision: 2})
    if err != nil {
        log.Fatal(err)
    }
}

func getStream(file string) beep.StreamSeekCloser {
    f, err := os.Open(file)
    if err != nil {
        log.Fatal(err)
    }

    streamer, _, err := mp3.Decode(f)
    if err != nil {
        log.Fatal(err)
    }

    return streamer
}
MarkKremer commented 3 months ago

Discussion continued in https://github.com/gopxl/beep/issues/148