使用NodeJS播放音频:非法音频-MPEG-Header

时间:2013-08-29 15:38:08

标签: javascript node.js audio

我正在尝试从网络服务器播放音频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);
   });
};

player.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事件之前发生了一些错误。跟踪播放直到结束。然而,当我尝试运行相同的东西时,它甚至都没有启动。有什么想法吗?

0 个答案:

没有答案