继续Node - how can i pipe to a new READABLE stream?
我正在尝试使用num_samples
和ReadStream
为我的实时编码的MP3文件创建一个新的fs.watch
,当它达到一定的大小时(基本上是缓冲前)。
它可以工作,但是一旦fs.stat
开始,我就不知道如何退出观察者并保持流运行。
我已经尝试了如下的承诺,但是永远不会解决,所以重复调用ReadStream
:
streamEncodedFile
我的另一个可悲的尝试是尝试仅以特定文件大小启动流:
var watcher = fs.watch(mp3RecordingFile);
watcher.on('change', (event, path) => {
fs.stat(mp3RecordingFile, function (err, stats) {
if (stats.size > 75533) {
new Promise(function(resolve, reject) {
streamEncodedFile();
})
.then(function(result) {
watcher.close();
console.log('watcher closed');
});
}
});
});
function streamEncodedFile() {
var mp3File = fs.createReadStream(mp3RecordingFile);
mp3File.on('data', function(buffer){
io.sockets.emit('audio', { buffer: buffer });
});
}
答案 0 :(得分:0)
尝试此解决方案,缓冲并写入文件。
const Writable = require('stream').Writable;
const fs = require('fs');
let mp3File = fs.createWriteStream('path/to/file.mp3');
var buffer = new Buffer([]);
//in bytes
const CHUNK_SIZE = 102400; //100kb
//Proxy for emitting and writing to file
const myWritable = new Writable({
write(chunk, encoding, callback) {
buffer = Buffer.concat([buffer, chunk]);
if(buffer.length >= CHUNK_SIZE) {
mp3File.write(buffer);
io.sockets.emit('audio', { buffer: buffer});
buffer = new Buffer([]);
}
callback();
}
});
myWritable.on('finish', () => {
//emit final part if there is data to emit
if(buffer.length) {
//write final chunk and close fd
mp3File.end(buffer);
io.sockets.emit('audio', { buffer: buffer});
}
});
inbound_stream.pipe(encoder).pipe(myWritable);