问题描述
我对Vue.js编程非常陌生,我想做的是一个简单的录音机,单击录音按钮即可开始录制音频,单击停止按钮则可以停止录制。停止时,应在模板中显示音频文件,并将音频存储在Blob中,然后将其存储在本地。
我已经实现了如下模板:
<template>
<!-- Voice Record Title + Button -->
<div class="form-group row">
<label for="Audio" class="col-2 col-form-label labelTop">Audio</label>
<div class="col-1">
<button @click="recordAudio()" type="button" id="button_record" class="btn btn-danger">
</button>
<button type="button" id="button_stop" class="btn btn-success">
</button>
<div id="audio" class="audio" controls>
</div>
</div>
</div>
</template>
该脚本包含以下代码:
export default {
methods: {
recordAudio() {
var device = navigator.mediaDevices.getUserMedia({ audio: true });
var items = [];
device.then((stream) => {
var recorder = new MediaRecorder(stream);
recorder.ondataavailable = (e) => {
items.push(e.data);
if (recorder.state == "inactive") {
var blob = new Blob(items,{ type: "audio/*" });
var audio = document.getElementById("audio");
var mainaudio = document.createElement("audio");
mainaudio.setAttribute("controls","controls");
audio.appendChild(mainaudio);
mainaudio.innerHTML =
'<source src="' +
URL.createObjectURL(blob) +
'" type="audio/*" />';
}
};
recorder.start();
// I do not want a timeout to stop the recording but clicking the stop button to do so
setTimeout(() => {
recorder.stop();
},5000);
});
},},};
这听起来很简单,但是我现在要做的唯一一件事是,它会在几秒钟后停止使用此超时功能停止录制,而不是在单击button_stop
时停止录制。
我尝试了很多事情,例如使用
button_stop
@click="recorder.stop()"
或:
if (document.getElementById("button_stop").clicked == true) {
recorder.stop();
}
还有:
document.getElementById("button_stop").addEventListener("click",recorder.stop());
if (document.getElementById("button_stop").clicked == true) {
recorder.stop();
}
但是这些都不是真的。
由于我对Vue和Java语言刚起步,这真的让我感到沮丧。 我真的很感谢您的帮助。
解决方法
您应该能够通过将recorder
分配给组件中的变量(不仅是函数中的变量)来实现此目的。这样,您以后就可以在单击按钮时调用this.recorder.stop()
。
尝试:
data() {
return {
recorder: null
}
},methods: {
recordAudio() {
var device = navigator.mediaDevices.getUserMedia({ audio: true });
device.then((stream) => {
// use this!
this.recorder = new MediaRecorder(stream);
this.recorder.ondataavailable = (e) => {
// ....
};
});
},// called on button click
stop() {
this.recorder.stop()
}
}
模板:
<button type="button" id="button_stop" class="btn btn-success" @click="stop">