javascript - 带有两个按钮的录音功能,一个用于开始录音,另一个用于停止录音
问题描述
我对 Vue.js 编程非常陌生,我想做的是一个简单的录音机,它在单击录制按钮时开始录制音频,并在单击停止按钮时停止录制。停止时,它应在模板中显示音频文件并将音频存储在 blob 中,该 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
with
@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 和 Javascript 很陌生,这真的让我很沮丧。我真的很感激任何帮助。
解决方案
您应该能够通过分配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">
推荐阅读
- python - Docker:运行图像不会在主机上产生 Pandas 数据帧输出
- java - JavaFX WebView Css 转换不起作用
- azure - 无法在 PostMan 中获取 Azure AD 令牌
- python - 将带有命名列表的字典转换为 pandas DataFrame
- docker - 在 compose 文件中配置了 GPU 的 Docker 服务;Keras 无法识别 GPU
- react-native - React Native Gifted Chat - 视频消息不可点击
- vue.js - 为什么 webpack 无法加载从 vue 组件导入的 *.js 类?
- android - 为什么某些 Android 设备可能会使用更多的图形内存来运行相同的应用程序?
- javascript - Javascript:正确导出时不知道导入的标识符
- common-lisp - 通过 Quicklisp 在 Mac 上安装 SBCL CFFI 包时出现包锁定错误