[英]Node.js audio player
I basically want to play a series of mp3-files after each other. 我基本上想要互相播放一系列mp3文件。 It shouldn't be to hard, but I'm struggling to keep the decoder and speaker channel open to feed new mp3 data in after a song has been played. 它应该不是很难,但我很难保持解码器和扬声器通道打开,以便在播放一首歌后输入新的mp3数据。 Here is a condensed version from what I have so far, playing one mp3 file. 这是我到目前为止的一个浓缩版本,播放一个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
});
I'm using TooTallNate's modules node-lame (for decoding) and node-speaker (for audio output through the speakers). 我正在使用TooTallNate的模块node-lame (用于解码)和node-speaker (用于通过扬声器输出音频)。
No experience whatsoever with the modules you mention, but I think you need to reopen the speaker each time you want to play a song (since you pipe the decoded audio to it, it will be closed once the decoder is done). 没有任何关于你提到的模块的经验,但我认为你每次想要播放一首歌时都需要重新打开扬声器(因为你将解码后的音频传输给它,一旦解码完成就会关闭它)。
You could rewrite your code to something like this (untested); 您可以将代码重写为此类(未经测试);
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);
Another solution (one which I would prefer) is to use the very nice async module: 另一个解决方案(我更喜欢的是)使用非常好的异步模块:
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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.