Skip to content

Instantly share code, notes, and snippets.

@Cretezy
Last active October 13, 2021 01:34
Show Gist options
  • Save Cretezy/3623fecb1418e21b5d1f77db50fc7e07 to your computer and use it in GitHub Desktop.
Save Cretezy/3623fecb1418e21b5d1f77db50fc7e07 to your computer and use it in GitHub Desktop.
ShoutPlay.js

Simple script to stream a file from Node.js to Icecast (or any libshout compatible server) using nodeshout.

Usage

const shout = ... // Shout instance
const songPath = 'song.ogg';
const playing = play(shout, songPath);
playing.on("finish", ()=>{
  // Do something (e.g.: play next song)
});
playing.on("error", (error)=>{
  // An error happened, oh no
  console.warn(error);
});
const nodeshout = require("nodeshout");
const Writable = require('stream').Writable;
const EventEmitter = require('events');
const fs = require("fs");
module.exports = function (shout, filepath) {
const events = new EventEmitter();
let playing = true;
console.log('Starting to play', filepath);
const shoutStream = new Writable();
shoutStream._write = (chunk, encoding, next) => {
if (playing) {
const sent = shout.send(chunk, chunk.length);
if (sent !== nodeshout.ErrorTypes.SUCCESS) {
const errorMessage = `Error sending to shout: ${getShoutErrorCode(sent)} (code ${sent})`;
events.emit("error", new Error(errorMessage))
}
setTimeout(next, Math.abs(shout.delay()));
}
};
shoutStream.on("finish", () => {
if (playing) {
playing = false;
events.emit("finish")
}
});
const fileStream = fs.createReadStream(filepath);
fileStream.pipe(shoutStream);
fileStream.on('error', (error) => {
events.emit("error", error)
});
events.on("stop", () => {
playing = false;
try {
fileStream.unpipe(shoutStream);
fileStream.destroy();
fileStream.close();
} catch (e) {
}
});
return events;
};
// Get error code title
function getShoutErrorCode(code) {
return Object.keys(nodeshout.ErrorTypes).find((key) => {
return code === nodeshout.ErrorTypes[key]
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment