J
J
Jedi2018-12-15 04:29:59
Node.js
Jedi, 2018-12-15 04:29:59

How to implement streaming?

Good morning!
How to implement audio streaming in Nodejs platform?
I want to implement a player, but now I need to correctly implement streaming, because a lot depends on it.
Thanks to!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-12-15
@PHPjedi

example.js

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.html'));
})

app.get('/audio', function(req, res) {
  const path = 'sample.mp3';
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;

  if (range) {
    const parts = range.replace(/bytes=/, '').split('-');
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

    const chunksize = (end-start) + 1;
    const file = fs.createReadStream(path, {start, end});
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'audio/mpeg',
    };

    res.writeHead(206, head);
    file.pipe(res);
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'audio/mpeg',
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

app.listen(8000, function () {
  console.log('Listening on port 8000!');
});

<html>
  <head>
    <title>Example</title>
  </head>
  <body>
    <audio id="audioPlayer" controls>
      <source src="http://localhost:8000/audio" type="audio/mpeg">
    </audio>
  </body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question