Tuesday, October 6, 2015

Html5 audio streaming problem with nodejs express module, the time handler doesn't moved while playing



Html5 audio problem: time handler isn't moved while playing 

I have a simple web server with nodejs and express module
This is structure



File server.js: 

Use express module to response file index.html and url '/audio' (which return file song.mp3)
When request is '/audio', server will read file song.mp3 and streaming to client
fs.createReadStream('song.mp3').pipe(res);

Source server.js
var express = require("express");var fs = require("fs");var app = express();
app.get('/', function(req, res){
    res.sendFile(__dirname+'/index.html');});
app.get('/audio', function(req, res){
    console.log("send file mp3")
    fs.createReadStream('song.mp3').pipe(res);});
app.get(/^(.+)$/, function(req, res){
    console.log("static file request: " + req.params);    res.sendFile(__dirname + req.params[0]);});
app.listen(3000, function(){
   console.log("Listening on port 3000");});


File index.html

This page just contains an audio control with src point to '/audio'
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Html5 Audio player</title></head><body><audio src="/audio" type="audio/mp3" controls></audio></body></html>

Open url localhost:3000

And the response header



Problem

Audio control doesn't know audio duration.
When click button play, current time number works but the time handler doesn't move.

Reason

Because server streaming audio file to client, audio control doesn't know the length of audio file. It cause problem the time handler doesn't move while playing

Solution

Before streaming audio file, set header Content-length
var stat = fs.statSync('song.mp3');res.set('Content-Length', stat.size);

Restart server nodejs and run again.


Source code: download