Skip to content

Commit

Permalink
more stable streaming audio play and save (#477)
Browse files Browse the repository at this point in the history
* more stable streaming audio play and save

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
Jalen-Zhong and pre-commit-ci[bot] authored Aug 19, 2024
1 parent 027bfe1 commit 5a842d1
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions tools/post_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import base64
import json
import wave
from pathlib import Path

import pyaudio
Expand Down Expand Up @@ -129,12 +130,27 @@ def play_audio(audio_content, format, channels, rate):
stream = p.open(
format=audio_format, channels=args.channels, rate=args.rate, output=True
)
for chunk in response.iter_content(chunk_size=1024):
if chunk:
stream.write(chunk)
stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open("generated_audio.wav", "wb")
wf.setnchannels(args.channels)
wf.setsampwidth(p.get_sample_size(audio_format))
wf.setframerate(args.rate)

stream_stopped_flag = False

try:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
stream.write(chunk)
wf.writeframesraw(chunk)
else:
if not stream_stopped_flag:
stream.stop_stream()
stream_stopped_flag = True
finally:
stream.close()
p.terminate()
wf.close()
else:
audio_content = response.content

Expand Down

0 comments on commit 5a842d1

Please sign in to comment.