Node.js Electron 离线中文语音朗读:无需 appId 和 appKey 的百度语音合成 SDK 使用教程
本教程推荐使用百度语音合成技术,它提供了离线语音合成 SDK,可用于在不联网的情况下实现离线语音合成功能。
在 Node.js Electron 中使用百度语音合成 SDK,可以按照以下步骤:
-
下载离线语音合成 SDK,解压缩后将其中的 'libs' 和 'include' 文件夹复制到本地项目目录中。
-
安装 'node-gyp' 和 'ffi-napi' 模块,用于编译和加载 C++ 模块:
npm install -g node-gyp
npm install ffi-napi
- 创建 C++ 模块,用于调用 SDK 中的接口。可以使用 'node-gyp' 命令行工具来生成模板代码:
node-gyp configure
node-gyp build
生成的模块文件位于 'build/Release' 目录下。
- 在 Node.js 中调用 C++ 模块,实现语音合成功能。可以在主进程中创建 'BrowserWindow' 实例,并在渲染进程中调用主进程中的语音合成函数。
以下是一个示例代码,实现了将文本转换为 MP3 音频文件,并使用 Electron 的播放器播放音频文件:
// 引入 Electron 和 Node.js 内置模块
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
// 引入 ffi 模块
const ffi = require('ffi-napi');
// 配置离线语音合成 SDK 路径
const libPath = path.join(__dirname, 'libs', 'libBDSpeechDecoder_V1.0.0.dylib');
const includePath = path.join(__dirname, 'include');
// 创建 C++ 模块
const speechSynthesis = ffi.Library(libPath, {
'bd_text_to_speech': ['int', ['string', 'string', 'string']]
});
// 创建主窗口
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// 加载 HTML 页面
mainWindow.loadFile('index.html');
// 打开开发者工具
mainWindow.webContents.openDevTools();
// 监听渲染进程的消息
ipcMain.on('speechSynthesis', async (event, { text }) => {
// 调用语音合成函数
const mp3Path = path.join(__dirname, 'output.mp3');
const ret = speechSynthesis.bd_text_to_speech(text, mp3Path, includePath);
if (ret === 0) {
// 播放音频文件
const audio = new Audio(mp3Path);
await audio.play();
} else {
console.error(`语音合成失败,错误码:${ret}`);
}
});
// 关闭窗口时触发
mainWindow.on('closed', function () {
mainWindow = null;
});
}
// 应用程序就绪时触发
app.on('ready', createWindow);
// 所有窗口关闭时触发
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
// 应用程序激活时触发
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
在渲染进程中,可以通过 'ipcRenderer' 模块向主进程发送消息,触发语音合成功能:
// 引入 Electron 和 Node.js 内置模块
const { ipcRenderer } = require('electron');
// 获取文本框和播放按钮元素
const textarea = document.querySelector('textarea');
const button = document.querySelector('button');
// 点击播放按钮时触发
button.addEventListener('click', async () => {
// 向主进程发送消息,触发语音合成功能
ipcRenderer.send('speechSynthesis', { text: textarea.value });
});
在实际使用中,可以根据需要修改 C++ 模块的代码,调整语音合成的参数和输出格式。例如,可以使用 PCM 格式输出音频数据,而不是生成 MP3 文件。
总之,使用百度语音合成 SDK 可以方便地实现离线语音合成功能,在没有网络连接的情况下也能够正常工作。
原文地址: https://www.cveoy.top/t/topic/nfBQ 著作权归作者所有。请勿转载和采集!