2017-03-04 72 views
3

我創建了一個簡單的服務器,它使用fs模塊將mp3文件流式傳輸到瀏覽器,並在html5音頻元素中播放它。實際上,音頻流完美無瑕,但是,即使我尋求的部分已經被緩衝了,我也無法通過流來尋找。節點 - 找不到音頻流

var express = require('express'); 
var app = express(); 
var fs = require('fs'); 

app.get('/', function (req, res) { 
    var filePath = 'music.mp3'; 
    var stat = fs.statSync(filePath); 

    res.writeHead(200, { 
     'Content-Type': 'audio/mpeg', 
     'Content-Length': stat.size, 
    }); 

    var readStream = fs.createReadStream(filePath); 
    readStream.pipe(res); 
}); 

其他類似Q &至於建議添加的內容範圍頭,但我無法找到如何做一個簡單的例子。其他人表示使用206 Partial-Content標題,但是當我這樣做時,音頻根本無法播放。

下面是this question

回答

4

調整代碼demo(在Chrome Windows版測試)從接受的答案之一:

var express = require('express'), 
    bodyParser = require('body-parser'), 
    fs = require('fs'), 
    path = require('path'), 
    app = express() 

app.get('/', function (req, res) { 
    var filePath = 'music.mp3'; 
    var stat = fs.statSync(filePath); 
    var total = stat.size; 
    if (req.headers.range) { 
     var range = req.headers.range; 
     var parts = range.replace(/bytes=/, "").split("-"); 
     var partialstart = parts[0]; 
     var partialend = parts[1]; 

     var start = parseInt(partialstart, 10); 
     var end = partialend ? parseInt(partialend, 10) : total-1; 
     var chunksize = (end-start)+1; 
     var readStream = fs.createReadStream(filePath, {start: start, end: end}); 
     res.writeHead(206, { 
      'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 
      'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 
      'Content-Type': 'video/mp4' 
     }); 
     readStream.pipe(res); 
    } else { 
     res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'audio/mpeg' }); 
     fs.createReadStream(path).pipe(res); 
    } 
});