簡體   English   中英

在NodeJS中提供mp3文件以在音頻標簽中使用

[英]Serving mp3 files in NodeJS for use in audio tag

我在NodeJS中提供mp3文件時遇到問題。

var filestream = fs.createReadStream('file.mp3');
filestream.on('open', function() {
  var stats = fs.statSync('file.mp3');
  var fileSizeInBytes = stats["size"];
  response.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': fileSizeInBytes});
  filestream.pipe(response);
});

我正在設置文件的內容類型,然后再提供它們以及內容的長度。

當頁面上有文件時,我可以播放音頻並獲取內容的持續時間和當前時間。

但是我不能像現在不使用NodeJS來提供mp3文件一樣設置當前時間。

<audio id='player' src='file.mp3'></audio>
<script>
  var duration = player.duration; // 88 seconds
  var time = player.currentTime; // 0 seconds

  player.currentTime = 10;

  var time = player.currentTime; // 0 seconds
</script>

只是為了緩解心情-從目錄打開此頁面時(不使用nodejs作為服務器),我可以設置音頻元素的currentTime。 為什么是這樣?
謝謝你的幫助。

解決方案是在每個響應中添加“接受范圍”標頭,並使用“范圍”標頭修改對請求的響應,從標頭讀取字節范圍,並使用HTTP / 1.1 206響應代碼提供該內容。

字節頭的格式為bytes=<start>-<end> ,例如bytes=0-49

這是我更新的代碼:

var filestream = fs.createReadStream('file.mp3');
var range = request.headers.range.replace("bytes=", "").split('-');

filestream.on('open', function() {
  var stats = fs.statSync('file.mp3');
  var fileSizeInBytes = stats["size"];

  // If the start or end of the range is empty, replace with 0 or filesize respectively
  var bytes_start = range[0] ? parseInt(range[0], 10) : 0;
  var bytes_end = range[1] ? parseInt(range[1], 10) : fileSizeInBytes;

  var chunk_size = bytes_end - bytes_start;

  if (chunk_size == fileSizeInBytes) {
    // Serve the whole file as before
    response.writeHead(200, {
      "Accept-Ranges": "bytes",
      'Content-Type': 'audio/mpeg',
      'Content-Length': fileSizeInBytes});
    filestream.pipe(response);
  } else {
    // HTTP/1.1 206 is the partial content response code
    response.writeHead(206, {
      "Content-Range": "bytes " + bytes_start + "-" + bytes_end + "/" + fileSizeInBytes,
      "Accept-Ranges": "bytes",
      'Content-Type': 'audio/mpeg',
      'Content-Length': fileSizeInBytes
    });
    filestream.pipe(response.slice(bytes_start, bytes_end);
  }
});

這個答案是部分通過在GitHub上一個要點找到靈感在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM