【web】vue 播放后端(flask)发送的 mp3 文件

演示

在这里插入图片描述

后端(flask)

  • 后端返回的是 mp3 文件的 url,是可以直接在浏览器上打开后播放的
  • 处理跨域请求
    pip install flask-cors
    
from flask import Flask, request, jsonify
from flask_cors import CORS

# 我的 mp3 存放路径
audio_temp_dir = 'garbage_can'

# static_folder 下的文件,可以直接通过 url 访问
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
    # 处理 mp3 文件,得到文件名
    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>
	<!-- 演示中使用的是 element-plus 的 button 组件 -->
	<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', {
   
                // post 请求参数
            }).then(response => {
   
            	// 后端返回的数据是 { url : xxxx }
                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,就可以成功播放

相关推荐

  1. nginx 配置mp4文件播放

    2024-01-02 11:44:02       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-02 11:44:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-02 11:44:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-02 11:44:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-02 11:44:02       18 阅读

热门阅读

  1. 深入理解@Resource与@Autowired:用法与区别解析

    2024-01-02 11:44:02       36 阅读
  2. JDK下载地址

    2024-01-02 11:44:02       48 阅读
  3. GRU算法

    GRU算法

    2024-01-02 11:44:02      32 阅读
  4. ansible搭建和基本使用

    2024-01-02 11:44:02       41 阅读
  5. 数据库-期末考前复习-第1章-绪论

    2024-01-02 11:44:02       32 阅读
  6. React 实现 Step组件

    2024-01-02 11:44:02       44 阅读
  7. react怎么实现跨页面传参

    2024-01-02 11:44:02       40 阅读