2

我正在尝试从网络服务器播放音频 mp3 文件而不将其下载到文件系统。这就是我获取此文件并播放它的方式:

var url = require('url');
var http = require('http');
var player = require('./player.js');

function initPlayback(res) {
   player.play(res);
   player.onPlaybackEnds(function() {
       console.log('Playback ends.');
   });
}

exports.add = function(file_url) {
   var options = {
       host: url.parse(file_url).host,
       port: 80,
       path: url.parse(file_url).pathname
   };
   http.get(options, function(res) {
       initPlayback(res);
   });
};

播放器.js

var fs = require('fs');
var lame = require('lame');
var Speaker = require('speaker');

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

var decoderMp3 = lame.Decoder();
var speaker = new Speaker(options);

var onPlaybackEnds = function() {};

function playMp3(dataStream) {
    speaker = new Speaker(options);
    decoderMp3 = lame.Decoder();
    dataStream.pipe(decoderMp3).pipe(speaker);

    speaker.on('flush', function() {
        onPlaybackEnds();
    });
}

exports.play = function(dataStream) {
    playMp3(dataStream);
};

exports.onPlaybackEnds = function(callback) {
    onPlaybackEnds = callback;
};

我从运行得到的输出add("http://localhost/file.mp3")是:

Note: Illegal Audio-MPEG-Header 0x41504554 at offset 201915.
Note: Trying to resync...
Note: Hit end of (available) data during resync.
Playback ends.

似乎在事件发生之前flush发生了一些错误。曲目播放直到结束。然而,当我尝试运行相同的东西时,它甚至都没有启动。有任何想法吗?

4

0 回答 0