1

I have an API endpoint that is streaming bytes of audio to me in real time in an mp3 format.

I want to know if I can start playing audio as soon as I start getting these bytes. How can I do this?

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=44100,
                output=True)


s = requests.Session()
with s.post(url, data=json.dumps(payload), headers=headers) as resp:
    for line in resp.iter_content():
        stream.write(line)

stream.stop_stream()
stream.close()
p.terminate()

However, I'm not hearing any audio. Is my stream incorrect?

1 Answers1

0

Found a solution.

s = requests.Session()
with s.post(url, data=json.dumps(payload), headers=headers) as resp:
    for line in resp.iter_content():
        if line:        
            audio_data = AudioSegment.from_mp3(io.BytesIO(line))
            raw_data = audio_data.raw_data
            stream.write(raw_data)

line should be a byte object.

Marvin Wa
  • 46
  • 5