electron 使用node js顺序播放多个wav文件
1、安装node-wav-player
npm install node-wav-player
2、代码实现,注意文件路径要正确,可以使用绝对路径
const wavPlayer = require('node-wav-player');
/**
* 顺序播放多个WAV音频文件
* @param {string[]} filePaths - WAV文件路径数组
* @param {Object} options - 播放选项
* @returns {Promise<void>}
*/
async function playWavFilesSequentially(filePaths, options = {}) {
const {
volume = 1.0, // 音量 0.0 - 1.0
interval = 0, // 文件间的间隔时间(毫秒)
loop = false // 是否循环播放
} = options;
if (!filePaths || filePaths.length === 0) {
console.log('没有提供音频文件路径');
return;
}
let currentIndex = 0;
try {
do {
const currentFile = filePaths[currentIndex];
//console.log(`正在播放: ${currentFile} (${currentIndex + 1}/${filePaths.length})`);
// 播放当前文件
await wavPlayer.play({
path: currentFile,
volume: volume,
sync: true // 同步播放,等待播放完成
});
//console.log(`播放完成: ${currentFile}`);
// 如果不是最后一个文件,等待间隔时间
if (currentIndex < filePaths.length - 1 && interval > 0) {
//console.log(`等待 ${interval}ms 后播放下一个文件...`);
await new Promise(resolve => setTimeout(resolve, interval));
}
currentIndex++;
// 如果循环播放且已播放完所有文件,重置索引
if (loop && currentIndex >= filePaths.length) {
// console.log('循环播放,重新开始...');
currentIndex = 0;
// 循环时的间隔
if (interval > 0) {
await new Promise(resolve => setTimeout(resolve, interval));
}
}
} while (loop || currentIndex < filePaths.length);
//console.log('所有音频文件播放完毕');
} catch (error) {
console.error('播放过程中发生错误:', error);
throw error;
}
}
/**
* 使用事件监听的方式播放(替代方案)
* @param {string[]} filePaths - WAV文件路径数组
*/
function playWavFilesWithEvents(filePaths) {
if (!filePaths || filePaths.length === 0) {
console.log('没有提供音频文件路径');
return;
}
let currentIndex = 0;
function playNext() {
if (currentIndex >= filePaths.length) {
console.log('所有音频文件播放完毕');
return;
}
const currentFile = filePaths[currentIndex];
//console.log(`正在播放: ${currentFile} (${currentIndex + 1}/${filePaths.length})`);
wavPlayer.play({
path: currentFile
}).then(() => {
// console.log(`播放完成: ${currentFile}`);
currentIndex++;
// 播放下一个文件
setTimeout(playNext, 100); // 小延迟确保稳定性
}).catch((error) => {
console.error(`播放文件失败: ${currentFile}`, error);
currentIndex++;
// 即使出错也继续播放下一个
setTimeout(playNext, 100);
});
}
// 开始播放
playNext();
}
// 使用示例
async function mainPlayer() {
const audioFiles = [
'./audio/sound1.wav',
'./audio/sound2.wav',
'./audio/sound3.wav'
];
try {
// 方法1: 使用async/await(推荐)
console.log('=== 顺序播放音频文件 ===');
await playWavFilesSequentially(audioFiles, {
volume: 0.8,
interval: 500, // 文件间间隔500ms
loop: false
});
// 方法2: 使用事件监听
// console.log('=== 使用事件监听方式播放 ===');
// playWavFilesWithEvents(audioFiles);
} catch (error) {
console.error('播放失败:', error);
}
}
// 导出函数供其他模块使用
module.exports = {
playWavFilesSequentially,
playWavFilesWithEvents
};

浙公网安备 33010602011771号