Selaa lähdekoodia

more stable streaming audio play and save (#477)

* 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>
Jalen Zhong 1 vuosi sitten
vanhempi
commit
5a842d1d40
1 muutettua tiedostoa jossa 22 lisäystä ja 6 poistoa
  1. 22 6
      tools/post_api.py

+ 22 - 6
tools/post_api.py

@@ -1,6 +1,7 @@
 import argparse
 import argparse
 import base64
 import base64
 import json
 import json
+import wave
 from pathlib import Path
 from pathlib import Path
 
 
 import pyaudio
 import pyaudio
@@ -129,12 +130,27 @@ if __name__ == "__main__":
             stream = p.open(
             stream = p.open(
                 format=audio_format, channels=args.channels, rate=args.rate, output=True
                 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:
         else:
             audio_content = response.content
             audio_content = response.content