Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1234

Python • Writing generated audio as FLAC?

$
0
0
I am trying to generate some audio and save it to a file as FLAC. I am misunderstanding several aspects, and the result is an "IndexError: tuple index out of range" error in the last line here:

Code:

#!/usr/local/venv/bin/python3import numpyimport pyaudioimport soundfile as sfduration   = 0.15    # base in seconds                                          amplitude  = 0.40    # range [0.0, 1.0]                                         sampleRate = 44100   # integer sample rate, Hz                                  frequency  = 440.0   # float sine frequency, Hz                                 # generate sine sample, with float32 array conversionsample = (numpy.sin(    numpy.arange(sampleRate * duration * 3) * frequency / sampleRate \    * numpy.pi * 2)).astype(numpy.float32)data = (amplitude * sample).tobytes() \    + (0 * sample).tobytes() \    + (amplitude * sample).tobytes()audio = pyaudio.PyAudio()stream = audio.open(format=pyaudio.paFloat32,                    channels=2,                    rate=sampleRate,                    output=True)# stream.write(data)                                       sf.write('audio.flac', data, sampleRate)
I would be grateful for tips on how to get past the error, or even about better approaches.

If uncommented, the stream.write() produces sound on the speakers. So I know there is a stream to write. I am just not finding the way to get the stream into stand alone FLAC file on the disk. Or Ogg would also be good. MP3 would be acceptable to, though.

Statistics: Posted by tpyo kingg — Thu Jan 18, 2024 2:49 pm



Viewing all articles
Browse latest Browse all 1234

Trending Articles