Skip to content

Instantly share code, notes, and snippets.

@kuu
Created July 20, 2020 03:20
Show Gist options
  • Save kuu/7f3dcf24577ba9a7cc3f4d5496eef21e to your computer and use it in GitHub Desktop.
Save kuu/7f3dcf24577ba9a7cc3f4d5496eef21e to your computer and use it in GitHub Desktop.
Sample code for extracting audio from RTMP stream
const fs = require('fs');
const path = require('path');
const {Writable, Transform} = require('stream');
const {writeData, type: {FLVFile, FLVHeader, FLVTag}} = require('@mediafish/flv');
const {createSimpleServer} = require('@mediafish/rtmp-server');
class Terminator extends Writable {
constructor() {
super({objectMode: true});
}
_write(chunk, encoding, cb) {
setImmediate(cb);
}
}
class AudioExtractor extends Transform {
constructor() {
super({objectMode: true});
this.header = new FLVHeader({version: 1, hasAudio: true, hasVideo: false});
this.tags = [];
}
_transform(obj, _, cb) {
const {type, timestamp, data} = obj;
if (type === 'audio') {
this.tags.push(new FLVTag({type: FLVTag.TagType.audio, timestamp, data}));
}
cb(null, obj);
}
_flush(cb) {
const flv = new FLVFile(this.header, this.tags);
const byteLength = writeData(flv, null, 0);
const buf = Buffer.alloc(byteLength);
writeData(flv, buf, 0);
const filePath = path.join(__dirname, 'audio.flv');
fs.writeFile(filePath, buf, err => {
if (err) {
return console.error(err.stack);
}
console.log(`A file writen to ${filePath}`);
cb();
});
}
}
createSimpleServer('/live')
.pipe(new AudioExtractor())
.on('finish', () => {
console.log('Finish!');
})
.on('error', err => {
console.error(err.stack);
})
.pipe(new Terminator());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment