重新开始写入流节点js

时间:2018-12-29 16:36:44

标签: javascript node.js fs

我有一个设置为通过http录制实时流音频的应用程序。我正在做一些音频处理,然后将生成的音频记录到文件中。录制30秒后,我想停止录制并保存文件(然后上传)。当我需要再开始录制30秒时,我会继续处理音频以寻找下一个点。我遇到的问题是,在我第一次停止录制后,当我想第二次开始录制时,总是出现错误。

错误是:Error: write after end

我想这与encoder.end()行有关

我还能如何停止录音,但是以后又可以重新开始呢?

var encoder = new lame.Encoder({
  // input
  channels: 1,        // 2 channels (left and right)
  bitDepth: 16,       // 16-bit samples
  sampleRate: 44100,  // 44,100 Hz sample rate
 
  // output
  bitRate: 128,
  outSampleRate: 22050,
  mode: lame.MONO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
});


var recordingDecoder;
module.exports.startRecording = function(decoder) {
	if(isRecording)
		return false;

	recordingDecoder = decoder;
	isRecording = true;
	recordingDecoder.pipe(encoder);
	var writeStream = fs.createWriteStream('../recorded_calls/currentCall.wav');
	encoder.pipe(writeStream);

}

module.exports.stopRecording = function() {
	if(isRecording) {
		console.log('stop recording', encoder)
		encoder.end();
		isRecording = false;
	}
	
}

编辑: 添加了unripe(),然后删除了文件。

module.exports.stopRecording = function() {
	if(isRecording) {
		console.log('stop recording')
		recordingDecoder.unpipe(encoder);
		isRecording = false;
	}
	
}

编辑:基于有关使用多个编码器的建议,我移动了要在startRecording函数中创建的编码器,然后在完成记录后将其设置为false。

var encoder;


var recordingDecoder;

module.exports.startRecording = function(decoder) {


	encoder = new lame.Encoder({
		// input
		channels: 1,        // 2 channels (left and right)
		bitDepth: 16,       // 16-bit samples
		sampleRate: 44100,  // 44,100 Hz sample rate

		// output
		bitRate: 128,
		outSampleRate: 22050,
		mode: lame.MONO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO
	});


	console.log('strat recording')

	if(isRecording)
		return false;

	recordingDecoder = decoder;
	isRecording = true;
	recordingDecoder.pipe(encoder);
	var writeStream = fs.createWriteStream('../recorded_calls/currentCall.wav');
	encoder.pipe(writeStream);





}

module.exports.stopRecording = function() {
	if(isRecording) {
		console.log('stop recording')
		recordingDecoder.unpipe(encoder);
		isRecording = false;
		encoder = false;
	}
	
}

1 个答案:

答案 0 :(得分:3)

结束在管道中间的流就像在水管中间关闭阀门一样,这将在水仍在流动或流仍在为数据提供服务时在阀门上产生压力。相反,您想unpipe来自编码器的记录,然后可以在以后再pipe对其进行记录。如果较长时间取消管道传输,则完全关闭流并在下次使用时重新创建它可能是有益的。