wujingjing
2025-04-02 f07405d8787e8bbd43453c81ec4f599dc34153b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import axios from 'axios';
import { ElMessage } from 'element-plus';
 
const audio = new Audio();
 
const synthesizeSpeech = async (text) => {
    try {
        if (!text) {
            ElMessage.warning('请输入要转换的文字');
            return;
        }
 
        const result = await speechByBaidu(text);
        if (result) {
            audio.src = result;
            audio.play();
        } else {
            ElMessage.error('语音合成失败');
        }
    } catch (error) {
        ElMessage.error('语音合成发生错误');
    }
};
 
const API_KEY = 'GFTyCZOmwuMz91A8jpkLqV0x';
const SECRET_KEY = '3Tcfi1DsyG4UzcT0ec1opLKtvIj1SIZe';
// 获取百度 access token 的函数
const getBaiduToken = function getAccessToken() {
    const options = {
        method: 'POST',
        url: '/api/baidu/speech_token?grant_type=client_credentials&client_id=' + API_KEY + '&client_secret=' + SECRET_KEY,
    };
    return new Promise((resolve, reject) => {
        axios(options)
            .then((res) => {
                resolve(res.data.access_token);
            })
            .catch((error) => {
                reject(error);
            });
    });
};
 
const createSpeechTask = async (text, token) => {
    const options = {
        method: 'POST',
        url: '/api/baidu/speech_synthesis/create?access_token=' + token,
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        data: JSON.stringify({
            text: text,
            format: 'mp3-16k',
            voice: 0,
            lang: 'zh',
            speed: 5,
            pitch: 5,
            volume: 5,
            enable_subtitle: 0,
        }),
    };
    return new Promise((resolve, reject) => {
        axios(options)
            .then((response) => {
                resolve(response.data.task_id);
            })
            .catch((error) => {
                reject(error);
            });
    });
};
 
const querySpeechTask = async (taskId, token) => {
    const options = {
        method: 'POST',
        url: '/api/baidu/speech_synthesis/query?access_token=' + token,
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        data: JSON.stringify({
            task_ids: [taskId],
        }),
    };
 
    return new Promise((resolve, reject) => {
        const checkStatus = async (resolve, reject) => {
            axios(options)
                .then(async (response) => {
                    const taskStatus = response.data.tasks_info?.[0]?.task_status;
                    if (!taskStatus) {
                        reject(new Error('语音合成失败'));
                        return;
                    }
                    const info = response.data.tasks_info?.[0];
                    if (taskStatus === 'Success') {
                        const url = info.task_result.speech_url;
                        resolve(url);
                    } else if (taskStatus === 'Running') {
                        setTimeout(() => {
                            checkStatus(resolve, reject);
                        }, 1000);
                    } else {
                        reject(new Error('语音合成失败'));
                    }
                })
                .catch((error) => {
                    reject(error);
                });
        };
        checkStatus(resolve, reject);
    });
};
 
const speechByBaidu = async (text) => {
    const token = await getBaiduToken();
    const taskId = await createSpeechTask(text, token);
    const result = await querySpeechTask(taskId, token);
    return result as string;
};