演示
后端(flask)
后端返回的是 mp3
文件的 url
,是可以直接在浏览器上打开后播放的 处理跨域请求pip install flask-cors
from flask import Flask, request, jsonify
from flask_cors import CORS
audio_temp_dir = 'garbage_can'
app = Flask( __name__, static_folder= f'./ { audio_temp_dir} ' )
CORS( app, supports_credentials= True )
@app. route ( "/" )
def hello_world ( ) :
return "<p>Hello, World!</p>"
@app. route ( "/speech" , methods= [ 'POST' ] )
def transfer_text_to_speech ( ) :
request_data = request. json
file_name = do_something( )
return jsonify( {
"""
request.host_url : 后端 url(app.run() 时,控制台打印的那个 url)
audio_temp_dir: 音频文件存放的文件夹(自定义的)
file_name: mp3 文件
"""
'url' : f' { request. host_url} { audio_temp_dir} / { file_name} '
} )
if __name__ == '__main__' :
app. run( port= 5001 )
前端(vue3)
< template>
< button type = " primary" @click = " handleAudio" " > 播放</ button>
< audio ref = " audioPlayer" controls >
< source :src = " audioUrl" type = " audio/mpeg" >
Your browser does not support the audio element.
</ audio>
</ template>
export default {
name : "你的组件名" ,
data ( ) {
return {
audioUrl : null
}
} ,
}
methods : {
handleAudio ( ) {
axios. post ( 'http://127.0.0.1:5000/speech' , {
} ) . then ( response => {
this . audioUrl = response. data. url;
this . $refs. audioPlayer. src = this . audioUrl;
this . $refs. audioPlayer. play ( ) ;
console. log ( this . audioUrl)
} )
}
}
说明
我尝试在 vue
中使用 v-model
来设置 audio
标签的 src
,但是这样做无法正常播放音频 ,原因不明 如果通过设置标签的 ref
属性,再通过 this.$refs
设置 audio
标签的 src
,就可以成功播放