let audioChunks = []; let mediaRecorder; let stream; if (event.key === '1') { console.log('数字1键被按下了!'); navigator.mediaDevices.getUserMedia({ audio: true }).then(s => { stream = s; mediaRecorder = new MediaRecorder(stream); mediaRecorder.addEventListener('dataavailable', event => { audioChunks.push(event.data); }); mediaRecorder.start(); }) } console.log('audioChunks',audioChunks) if (event.key === '2') { console.log('数字2键被按下了!',audioChunks); mediaRecorder.stop(); stream.getTracks().forEach(track => track.stop()); const audioBlob = new Blob(audioChunks, { type: 'audio/wav' }); const reader = new FileReader(); reader.readAsDataURL(audioBlob); reader.onloadend = () => { const dataURI = reader.result; emitUIInteraction(JSON.stringify(dataURI)); console.log('dataURI', dataURI); // downloadAudio(dataURI) }; }这段代码,怎么改
时间: 2024-03-21 18:38:07 浏览: 154
如果您想在数字2键按下之前查看audioChunks数组中的数据,可以将console.log('audioChunks',audioChunks)移动到数字1键按下的回调函数中,如下所示:
```
let audioChunks = [];
let mediaRecorder;
let stream;
if (event.key === '1') {
console.log('数字1键被按下了!');
navigator.mediaDevices.getUserMedia({ audio: true }).then(s => {
stream = s;
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.addEventListener('dataavailable', event => {
audioChunks.push(event.data);
});
mediaRecorder.start();
});
console.log('audioChunks',audioChunks); // 将console.log移动到此处
}
if (event.key === '2') {
console.log('数字2键被按下了!',audioChunks);
mediaRecorder.stop();
stream.getTracks().forEach(track => track.stop());
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const reader = new FileReader();
reader.readAsDataURL(audioBlob);
reader.onloadend = () => {
const dataURI = reader.result;
emitUIInteraction(JSON.stringify(dataURI));
console.log('dataURI', dataURI);
// downloadAudio(dataURI)
};
}
```
这将确保您只在audioChunks数组中有数据时才会打印它。
阅读全文