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

Confused about initializing the speaker from a file #164

Closed cheryllium closed 9 months ago

cheryllium commented 9 months ago

In the tutorial, first we decode an mp3 file and then we used the format returned by the Decode function to call Speaker.Init()... But the tutorial also cautions not to call Speaker.Init every time we want to play something.

Shouldn't we have to call it every time we want to play a new file, using the new format returned by decoding the new file?

If not, is there a way I can initialize the speaker without having to decode a file first? For it seems neater if I can initialize the speaker first, then call a function to give it a song to play.

MarkKremer commented 9 months ago

The sample rate given to speaker.Init() is used to interpret the samples pulled from the streamers given to speaker.Play(). These streamers must produce samples in a matching sample rate to that what the speaker was initialized with.

Given a single audio file or multiple audio files with the same sample rate, this is easy: configure the speaker using the sample rate of the audio file. Just like you've done already.

If there are multiple audio files, and they have different sample rates then you need to choose what sample rate you want to send to the speaker. Then every Streamer you want to play must be converted to this sample rate before you give it to speaker.Play(). This can be done by passing it through beep.Resample(3, yourFormat.SampleRate, speakerSampleRate, yourMp3Streamer). Have a look at the function's docblock for a description of its arguments.

cheryllium commented 9 months ago

Thanks! That clears it up.