Do0rMaMu commited on
Commit
5635c14
1 Parent(s): c8c3aff

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +13 -13
main.py CHANGED
@@ -1,9 +1,8 @@
1
  from fastapi import FastAPI, Form
2
- from fastapi.responses import FileResponse
 
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
- FileResponse: The WAV file containing the synthesized speech.
24
  """
25
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
26
- output_file = temp_file.name
27
 
28
- # Synthesize speech and save to a WAV file
29
- with wave.open(output_file, 'wb') as wav_file:
 
 
 
30
  audio = voice.synthesize(text, wav_file)
31
 
32
- # Ensure the file exists and return it as a response
33
- if os.path.exists(output_file):
34
- return FileResponse(output_file, media_type='audio/wav', filename='output.wav')
35
- else:
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():