Vinz243
Vinz243

Reputation: 9956

Node.js how to stream audio file

I have a node.js and I'd like to stream audio files to browser. Here is my route handling it:

routes['/v1/tracks/:id/file'] = {
  get: async (ctx, next) => {
    let tracks = await File.find({
      trackId: ctx.params.id,
      sort: 'bitrate',
      direction: 'desc',
      limit: 3
    });
    let stat = fs.statSync(tracks[0].data.path);
    let mimeType = 'audio/mpeg';

    let opts = {}, res = 200;

    let resHeaders = {
      'Content-Type': mimeType,
      'Content-Length': stat.size,
      'Accept-Ranges': 'bytes'
    };
    if (ctx.headers.accept !== '*/*') {
      ctx.res.writeHead(200, resHeaders);
      return;
    }
    if (ctx.headers['range']) {
      let [b, range] = ctx.headers['range'].split('=');
      console.log(b, range);
      if (b === 'bytes') {
        let [start, end] = range.split('-');

        if (!end || end === '' || end < start)
          end = stat.size;

        opts = {
          start: start - 0,
          end: end - 0
        };

        res = 206;
        resHeaders['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;
      }
    }
    ctx.res.writeHead(res, resHeaders);

    ctx.body = fs.createReadStream(tracks[0].data.path, opts);
  }
}

Then when I try to access the URL in chrome, it send two requests.

First one:

Request Headers:
    GET /v1/tracks/ghHxLPNt8Fayfx1d/file HTTP/1.1
    Host: localhost:3000
    Connection: keep-alive
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Accept-Encoding: gzip, deflate, sdch, br
    Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Response Headers:
    HTTP/1.1 200 OK
    X-Powered-By: Express
    Content-Type: audio/mpeg
    Content-Length: 5986643
    Accept-Ranges: bytes
    Date: Fri, 23 Dec 2016 14:09:27 GMT
    Connection: keep-alive

Second one:

Request headers:
    GET /v1/tracks/ghHxLPNt8Fayfx1d/file HTTP/1.1
    Host: localhost:3000
    Connection: keep-alive
    Accept-Encoding: identity;q=1, *;q=0
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
    Accept: */*
    Referer: http://localhost:3000/v1/tracks/ghHxLPNt8Fayfx1d/file
    Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
    Range: bytes=0-
Response headers:
    HTTP/1.1 206 Partial Content
    X-Powered-By: Express
    Content-Type: audio/mpeg
    Content-Length: 5986643
    Accept-Ranges: bytes
    Content-Range: bytes 0-5986643/5986643
    Date: Fri, 23 Dec 2016 14:09:28 GMT
    Connection: keep-alive

However it doesn't work. Chrome just show a blank track with the play button, but nothing it doesn't show track length and I can't interact with it. Safari just shows loading.

EDIT:

If I remove a bunch of the code (everything about partial content) I can get it working but it won't let me go to a position, only play it from start to the end. Also I can download it with the code I wrote here (Ctrl + S) and then play it just fine

Upvotes: 0

Views: 3131

Answers (1)

Vinz243
Vinz243

Reputation: 9956

OK finally after digging a lot, a single byte was the cause of the problem.

New code:

if (ctx.headers['range']) {
  let [b, range] = ctx.headers['range'].split('=');
  console.log(b, range);
  if (b === 'bytes') {
    let [start, end] = range.split('-');

    if (!end || end === '' || end < start)
      end = stat.size - 1;

    opts = {
      start: start - 0,
      end: end - 0
    };

    res = 206;
    resHeaders['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;
    resHeaders['Content-Length'] = end - start + 1;
  }
}

See also Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Upvotes: 1

Related Questions