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;
|
};
|