我有这个工作代码从麦克风中获取音频:
var audioContext = window.AudioContext ? new window.AudioContext() :
window.webkitAudioContext ? new window.webkitAudioContext() :
window.mozAudioContext ? new window.mozAudioContext() :
window.oAudioContext ? new window.oAudioContext() :
window.msAudioContext ? new window.msAudioContext() :
undefined;
(...)
navigator[getUserMedia]({audio:true}, function(stream) {
media = audioContext.createScriptProcessor(stream);
js = audioContext.createJavaScriptNode(BUFFER_LENGTH, 2, 2);
js.onaudioprocess = function(e) {
sendAudio(e);
};
}
但是当我试图停止它时,在Chrome中工作正常并且在Firefox中,我收到一个错误,即media.mediaStream.stop不存在!!
采购代码:
(...)
media.mediaStream.stop();
js.disconnect();
快速修复我把try catch设置为null,但我不喜欢修复! 我能做什么?
答案 0 :(得分:1)
对于初学者,不推荐使用createJavaScriptNode,而是使用createScriptProcessor 这有效:
var audio_context;
var BUFF_SIZE = 512;
var microphone_data = {};
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
audio_context = new AudioContext();
console.log("cool audio context established");
} catch (e) {
alert('Web Audio API is not supported by this browser and/or its current config\n');
}
function process_microphone_buffer(event) {
var microphone_buffer = event.inputBuffer.getChannelData(0);
console.log('microphone_buffer.length ', microphone_buffer.length);
}
function on_error(e) {
console.log(e);
}
function start_microphone() {
microphone_data.microphone_stream = audio_context.createMediaStreamSource(microphone_data.media_stream);
microphone_data.script_processor_node = audio_context.createScriptProcessor(BUFF_SIZE, 1, 1);
microphone_data.script_processor_node.onaudioprocess = process_microphone_buffer;
microphone_data.microphone_stream.connect(microphone_data.script_processor_node);
microphone_data.microphone_stream.connect(audio_context.destination);
console.log('OK microphone stream connected');
}
function record_microphone() { // call this from your UI ... say a button
if (! navigator.getUserMedia) {
navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
}
navigator.getUserMedia(
{audio: true},
function(stream) {
microphone_data.media_stream = stream;
start_microphone();
},
on_error
);
}
function stop_microphone() { // call this from ... say a button
microphone_data.microphone_stream.disconnect();
microphone_data.script_processor_node.disconnect();
microphone_data.media_stream.stop();
microphone_data.script_processor_node.onaudioprocess = null;
console.log('... microphone now stopped') ;
}
小心