以下是一个使用Flask开发并调用百度语音识别API的完整语音识别系统代码示例。该系统支持用户上传音频文件(如WAV、MP3),通过百度API进行语音识别,并返回识别结果。代码分为后端Python和前端HTML两部分,并逐行解释。


一、后端Python代码(app.py

from flask import Flask, request, jsonify, render_template
import requests
import base64
import json

app = Flask(__name__)

# 百度语音识别API配置
API_KEY = "你的API密钥"
SECRET_KEY = "你的密钥"
ACCESS_TOKEN_URL = "https://openapi.baidu.com/oauth/2.0/token"
ASR_URL = "https://vop.baidu.com/server_api"

# 获取百度语音识别的访问令牌
def get_access_token():
    payload = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(ACCESS_TOKEN_URL, data=payload)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        raise Exception("获取令牌失败:" + response.text)

# 处理语音识别请求
@app.route('/recognize', methods=['POST'])
def recognize_speech():
    if 'audio' not in request.files:
        return jsonify({'error': '未上传音频文件'}), 400

    audio_file = request.files['audio']
    audio_data = audio_file.read()

    # 获取访问令牌
    access_token = get_access_token()

    # 准备语音识别参数
    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "format": audio_file.filename.split('.')[-1].lower(),
        "rate": 16000,  # 假设音频采样率为16kHz,需根据实际调整
        "channel": 1,  # 单声道
        "token": access_token,
        "cuid": "your_cuid",  # 可选参数,用于标识设备
        "speech": base64.b64encode(audio_data).decode('utf-8'),
        "len": len(audio_data)
    }

    # 发送识别请求
    response = requests.post(ASR_URL, headers=headers, data=json.dumps(payload))
    if response.status_code == 200:
        result = response.json()
        if result.get("err_no") == 0:
            return jsonify({'result': result.get("result")[0]})
        else:
            return jsonify({'error': result.get("err_msg")}), 400
    else:
        return jsonify({'error': 'API请求失败'}), 500

# 主页路由
@app.route('/')
def index():
    return render_template('index.html')

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

二、前端HTML代码(templates/index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>语音识别系统</title>
</head>
<body>
    <h1>上传音频进行语音识别</h1>
    <form action="/recognize" method="post" enctype="multipart/form-data">
        <input type="file" name="audio" accept="audio/*" required>
        <button type="submit">提交识别</button>
    </form>
    <div id="result"></div>

    <script>
        // 处理表单提交
        const form = document.querySelector('form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(form);
            const response = await fetch('/recognize', {
                method: 'POST',
                body: formData
            });
            if (response.ok) {
                const data = await response.json();
                document.getElementById('result').innerText = `识别结果:${data.result}`;
            } else {
                const error = await response.json();
                alert(`识别失败:${error.error}`);
            }
        });
    </script>
</body>
</html>

三、逐行代码解释

后端Python代码
  1. 导入模块

    import requests
    import base64
    
    • requests用于发送HTTP请求,base64用于音频数据编码。
  2. 配置百度API参数

    API_KEY = "你的API密钥"
    
  3. 获取访问令牌

    def get_access_token():
        response = requests.post(ACCESS_TOKEN_URL, data=payload)
        return response.json().get("access_token")
    
    • 通过OAuth2.0获取令牌,用于后续API调用。
  4. 处理语音识别请求

    @app.route('/recognize', methods=['POST'])
    def recognize_speech():
        audio_data = audio_file.read()
        access_token = get_access_token()
    
    • 读取上传的音频文件数据,获取访问令牌。
  5. 准备识别参数

    payload = {
        "format": "wav",  # 根据实际文件格式调整
        "rate": 16000,  # 音频采样率
        "speech": base64.b64encode(audio_data).decode('utf-8')
    }
    
    • 将音频数据编码为Base64字符串,发送给百度API。
  6. 发送识别请求

    response = requests.post(ASR_URL, headers=headers, data=json.dumps(payload))
    
    • 发送POST请求到百度语音识别API,解析返回结果。
  7. 返回识别结果

    return jsonify({'result': result.get("result")[0]})
    
    • 将识别结果以JSON格式返回给前端。
前端HTML代码
  1. 上传表单

    <form action="/recognize" method="post" enctype="multipart/form-data">
        <input type="file" name="audio" accept="audio/*" required>
    
    • 提供文件上传功能,限制为音频文件。
  2. 处理表单提交

    form.addEventListener('submit', async (e) => {
        const response = await fetch('/recognize', { body: formData });
        document.getElementById('result').innerText = `识别结果:${data.result}`;
    
    • 提交文件到后端,显示识别结果。

四、使用说明

  1. 配置API密钥

    • 在百度智能云创建应用,获取API_KEYSECRET_KEY,替换代码中的占位符。
  2. 运行环境

    • 安装依赖:pip install flask requests
    • 启动服务:python app.py(访问http://127.0.0.1:5000
  3. 上传音频

    • 选择WAV/MP3文件(需与后端配置的采样率和声道一致),提交后显示识别结果。

五、注意事项

  • 音频格式要求
    • 百度API支持PCM/WAV/AMR等格式,需确保采样率(如16kHz)和声道(单声道)正确。
  • 网络限制
    • 百度API需通过公网访问,乌鲁木齐地区网络需确保可访问百度服务。
  • 错误处理
    • 前端需处理识别失败情况,后端需捕获API异常(如令牌过期)。

该系统适用于需要集成语音识别功能的场景,例如语音命令处理、会议记录转写等。实际使用中需根据音频源调整参数(如采样率),并处理不同格式的兼容性。

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐