关于Vue中使用audio实现声音的播放

        在项目中需要实现点击播放声音。

一、引入资源

audio: new Audio(require("@/assets/wan_run/y1065.mp3"))

二、相关方法

// 播放声音
		playAudio() {
			if (this.audio.paused) {
                //防止重复播放
				this.paused = false;

				this.audio.play();
				this.audio.addEventListener("ended", this.handleAudioEnded);
			}
		},
// 监听声音播放结束
		handleAudioEnded() {
			this.paused = true;
		},
// 停止声音播放
		stopAudio() {
			this.audio.pause();
			this.paused = true;
			this.audio.currentTime = 0;
		},
// 点击声音
		changeAlarm(value) {
			if (value == "close") {
				this.stopAudio();
			} else {
				this.playAudio();
			}
		},

### 实现音频录制功能 为了在 Vue 项目中使用 `js-audio-recorder` 来实现音频录制功能,可以遵循以下方式构建应用逻辑。这不仅涉及组件内部的方法定义,还包括处理用户交互事件以及状态管理。 #### 安装依赖库 首先需要引入必要的 JavaScript 库来支持浏览器中的音频捕获能力。可以通过 npm 或者 yarn 添加 `js-audio-recorder` 到开发环境中[^2]: ```bash npm install js-audio-recorder --save ``` 或者 ```bash yarn add js-audio-recorder ``` #### 编写 Vue 组件代码 接下来是在 Vue 组件内编写具体的业务逻辑。下面是一个简单的例子展示如何创建一个具备基本录音控制(开始、停止)和播放已录声音片段的小部件[^5]: ```javascript import Recorder from 'js-audio-recorder'; export default { data() { return { recorder: null, kFlag: true, // 控制按钮显示与否的状态标志位 dFlag: false, setTime: undefined }; }, methods: { handleStart() { const that = this; that.recorder = new Recorder(); Recorder.getPermission() .then(() => { that.kFlag = false; that.dFlag = true; console.log('开始录音'); that.recorder.start(); // 开始录音 clearTimeout(that.setTime); that.setTime = setTimeout(function () { that.stopRecord(); alert('录音时间到'); }, 180000); // 设置最大录音时间为三分钟 }) .catch((error) => { that.$message({ message: '请先允许该网页使用麦克风', type: 'info' }); console.error(`${error.name}: ${error.message}`); }); }, stopRecord() { let that = this; that.recorder.stop().then(blob => { // 停止后的操作,比如保存blob对象用于后续播放或上传 console.log('录音结束', blob); // 可选:立即播放刚刚录制的内容 /*const audioUrl = URL.createObjectURL(blob); document.querySelector('#audioPlayer').src = audioUrl;*/ // 清理定时器和其他资源... clearTimeout(that.setTime); that.kFlag = true; that.dFlag = false; // 这里还可以加入更多处理逻辑,例如将Blob数据发送给服务器端等 }).catch(error => { console.error(`Error stopping recording: ${error.message}`); }); } } }; ``` 上述代码展示了如何初始化录音器实例,并通过监听用户的点击行为触发相应的录音动作。当调用 `handleStart()` 方法时会请求获取麦克风权限并启动录音;而 `stopRecord()` 负责终止当前正在进行的录音过程并将结果作为 Blob 对象返回以便进一步处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值