Search code examples
pythonflaskpostmantext-to-speechgtts

Using Flask to reproduce an audio using json


i'm trying to make an app in flask-python that using a json post send an audio using the gtts google library as the answer, but my method doesn't work. My code is the following.

from gtts import gTTS
from flask import Flask, send_file, request



app = Flask(__name__)

@app.route("/")
def t2s():
    text = request.get_json()
    obj = gTTS(text = text, slow = False, lang = 'en')    
    obj.save('audio.wav')
    return send_file('audio.wav')


if __name__ == "__main__":
    app.run(port=3000  , debug=True, use_reloader=True, host='0.0.0.0') 

any suggestions?, i'm using postman.

Thanks a lot for the possible help


Solution

  • Flask as default doesn't get POST requests and you have to use methods=['POST', 'GET']

    from gtts import gTTS
    from flask import Flask, send_file, request
    
    app = Flask(__name__)
    
    @app.route("/", methods=['POST', 'GET'])
    def t2s():
        text = request.get_json()
        print(text)
        obj = gTTS(text = text, slow = False, lang = 'en')    
        obj.save('audio.wav')
        return send_file('audio.wav')
    
    if __name__ == "__main__":
        app.run(host='0.0.0.0', port=3000) 
    

    And test (using mplayer on Linux):

    import requests
    import os
    
    data = 'Hello World'
    
    r = requests.post('http://127.0.0.1:3000/', json=data)
    
    open('output.wav', 'wb').write(r.content)
    
    os.system('mplayer output.wav')