Update main.py
Browse files
main.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
from fastapi import FastAPI, Form
|
| 2 |
-
from fastapi.responses import
|
|
|
|
| 3 |
import wave
|
| 4 |
from piper.voice import PiperVoice
|
| 5 |
-
import os
|
| 6 |
-
import tempfile
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
@@ -20,20 +19,21 @@ def synthesize_text(text: str = Form(...)):
|
|
| 20 |
text (str): The text to synthesize.
|
| 21 |
|
| 22 |
Returns:
|
| 23 |
-
|
| 24 |
"""
|
| 25 |
-
|
| 26 |
-
output_file = temp_file.name
|
| 27 |
|
| 28 |
-
# Synthesize speech and
|
| 29 |
-
with wave.open(
|
|
|
|
|
|
|
|
|
|
| 30 |
audio = voice.synthesize(text, wav_file)
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
return {"error": "Failed to generate audio."}
|
| 37 |
|
| 38 |
@app.get("/")
|
| 39 |
def read_root():
|
|
|
|
| 1 |
from fastapi import FastAPI, Form
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
import io
|
| 4 |
import wave
|
| 5 |
from piper.voice import PiperVoice
|
|
|
|
|
|
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
|
|
|
| 19 |
text (str): The text to synthesize.
|
| 20 |
|
| 21 |
Returns:
|
| 22 |
+
StreamingResponse: The audio data as a stream.
|
| 23 |
"""
|
| 24 |
+
audio_buffer = io.BytesIO()
|
|
|
|
| 25 |
|
| 26 |
+
# Synthesize speech and write to an in-memory WAV file
|
| 27 |
+
with wave.open(audio_buffer, 'wb') as wav_file:
|
| 28 |
+
wav_file.setnchannels(1) # Set the number of audio channels
|
| 29 |
+
wav_file.setsampwidth(2) # Set sample width to 2 bytes
|
| 30 |
+
wav_file.setframerate(16000) # Set the sampling rate
|
| 31 |
audio = voice.synthesize(text, wav_file)
|
| 32 |
|
| 33 |
+
# Seek to the beginning of the buffer so it can be read from the start
|
| 34 |
+
audio_buffer.seek(0)
|
| 35 |
+
|
| 36 |
+
return StreamingResponse(audio_buffer, media_type="audio/wav")
|
|
|
|
| 37 |
|
| 38 |
@app.get("/")
|
| 39 |
def read_root():
|