I'm using NodeJS to stream a MP3 file to a website, the idea is making something along the lines of Spotify. However, even though the user can see the progress moving through html tag which is receiving the audio stream, it's not possible to change it to advance or rewind the music e.g skip a minute or two of the song.
NodeJS code:
const express = require('express')
, app = express()
, fs = require('fs')
, getStat = require('util').promisify(fs.stat);
app.use(express.static('public'));
const highWaterMark = 32;
app.get('/audio', async (req, res) => {
const filePath = './tracks/mixaund-sunshine-day.mp3';;
const stat = await getStat(filePath);
console.log(stat);
res.writeHead(200, {
'Content-Type': 'audio/mp3',
'Connection': 'Keep-Alive',
'Transfer-encoding': 'chunked',
'Content-Length': stat.size
});
const stream = fs.createReadStream(filePath, { highWaterMark });
stream.on('end', () => console.log('End of streaming'));
stream.pipe(res);
});
app.listen(3000, () => console.log('app is running'));
Front-end client code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>client-side</title>
</head>
<body>
<audio controls>
<source src="/audio" type="audio/ogg">
</audio>
</body>
</html>
Add 'Accept-Ranges': 'bytes'
Header to Properly handle partial content
something like this
res.writeHead(200, {
'Content-Type': 'audio/mp3',
'Accept-Ranges': 'bytes',
'Connection': 'Keep-Alive',
'Transfer-encoding': 'chunked',
'Content-Length': stat.size
});