gpt4 book ai didi

javascript - Node.js 音频播放器

转载 作者:搜寻专家 更新时间:2023-10-31 23:18:34 29 4
gpt4 key购买 nike

我基本上想依次播放一系列 mp3 文件。这不应该太难,但我正在努力让解码器和扬声器 channel 保持打开状态,以便在播放完一首歌曲后输入新的 mp3 数据。这是我目前使用的压缩版本,播放一个 mp3 文件。

var audioOptions = {channels: 2, bitDepth: 16, sampleRate: 44100};

// Create Decoder and Speaker
var decoder = lame.Decoder();
var speaker = new Speaker(audioOptions);

// My Playlist
var songs = ['samples/Piano11.mp3','samples/Piano12.mp3','samples/Piano13.mp3'];

// Read the first file
var inputStream = fs.createReadStream(songs[0]);

// Pipe the read data into the decoder and then out to the speakers
inputStream.pipe(decoder).pipe(speaker);

speaker.on('flush', function(){
// Play next song
});

我正在使用 TooTallNate 的模块 node-lame (用于解码)和 node-speaker (用于通过扬声器输出音频)。

最佳答案

对您提到的模块没有任何经验,但我认为您每次想要播放歌曲时都需要重新打开扬声器(因为您将解码后的音频传输到扬声器,解码器完成后它将关闭)。

您可以将您的代码重写成这样(未经测试);

var audioOptions = {channels: 2, bitDepth: 16, sampleRate: 44100};

// Create Decoder and Speaker
var decoder = lame.Decoder();

// My Playlist
var songs = ['samples/Piano11.mp3','samples/Piano12.mp3','samples/Piano13.mp3'];

// Recursive function that plays song with index 'i'.
function playSong(i) {
var speaker = new Speaker(audioOptions);
// Read the first file
var inputStream = fs.createReadStream(songs[i]);
// Pipe the read data into the decoder and then out to the speakers
inputStream.pipe(decoder).pipe(speaker);
speaker.on('flush', function(){
// Play next song, if there is one.
if (i < songs.length - 1)
playSong(i + 1);
});
}

// Start with the first song.
playSong(0);

另一个解决方案(我更喜欢的一个)是使用非常好的 async模块:

var async = require('async');
...
async.eachSeries(songs, function(song, done) {
var speaker = new Speaker(audioOptions);
var inputStream = fs.createReadStream(song);

inputStream.pipe(decoder).pipe(speaker);

speaker.on('flush', function() {
// signal async that it should process the next song in the array
done();
});
});

关于javascript - Node.js 音频播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16927394/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com