当前位置: 首页 > web >正文

vue3 在线播放语音 mp3

播放、暂停、停止

<template><div><button @click="togglePlay">{{ isPlaying ? "暂停" : "播放" }}</button><button @click="stopAudio">停止</button><p>播放进度:{{ Math.round(progress) }}%</p></div>
</template><script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import audioSrc from "@/assets/mp3/stop.mp3";// 音频对象
let audio = null;// 播放状态
const isPlaying = ref(false);// 播放进度(百分比)
const progress = ref(0);// 初始化音频
onMounted(() => {audio = new Audio(audioSrc);// 监听播放进度audio.addEventListener("timeupdate", () => {progress.value = (audio.currentTime / audio.duration) * 100;});
});// 切换播放/暂停
const togglePlay = () => {if (isPlaying.value) {audio.pause();} else {audio.play().catch(error => {console.error("播放被阻止:", error);// 处理自动播放策略限制(需用户交互后才能播放)});}isPlaying.value = !isPlaying.value;
};// 停止播放
const stopAudio = () => {audio.pause();audio.currentTime = 0;progress.value = 0;
};// 组件卸载时清理资源
onBeforeUnmount(() => {audio.pause();audio.removeEventListener("timeupdate");
});
</script>

有时间轴

<template><div><audio ref="audioPlayer" controls><source :src="safeAudioUrl.mp3" type="audio/mpeg" /></audio><button @click="togglePlay">{{ isPlaying ? "暂停" : "播放" }}</button><p v-if="error">{{ error }}</p></div>
</template><script setup>
import { ref, computed } from "vue";
// 直接导入音频文件
import notificationSound from "@/assets/mp3/alarm.mp3";const audioPlayer = ref(null);
const isPlaying = ref(false);
const error = ref(null);const safeAudioUrl = computed(() => ({mp3: notificationSound
}));const togglePlay = () => {if (!audioPlayer.value) return;if (isPlaying.value) {audioPlayer.value.pause();} else {audioPlayer.value.play().catch(err => {error.value = `播放失败: ${err.message}`;});}isPlaying.value = !isPlaying.value;
};audioPlayer.value?.addEventListener("error", e => {console.log("1111111111e: ", e);const errors = {1: "MEDIA_ERR_ABORTED - 用户中止",2: "MEDIA_ERR_NETWORK - 网络错误",3: "MEDIA_ERR_DECODE - 解码错误",4: "MEDIA_ERR_SRC_NOT_SUPPORTED - 格式不支持"};error.value = errors[audioPlayer.value.error?.code] || "未知错误";
});
</script>

http://www.xdnf.cn/news/7296.html

相关文章:

  • 类和对象(3)--《Hello C++ World!》(5)(C/C++)--构造函数,析构函数和拷贝构造函数
  • Windows中PDF TXT Excel Word PPT等Office文件在预览窗格无法预览的终级解决方法大全
  • .NET外挂系列:2. 了解强大的 harmony 注解特性
  • 20.自动化测试框架开发之Excel配置文件的IO开发
  • 无需笔墨之功,锦绣SQL自成桥——QuickAPI古法炼数据秘术
  • 企业标准信息公共服务平台已开放标准通编辑器访问入口
  • 可视化图解算法41:搜索二维矩阵(二维数组中的查找)
  • 分布式ID生成系统
  • 深入解析OkHttp与Retrofit:Android网络请求的黄金组合
  • 深度解析:Redis 性能优化全方位指南
  • 在windows下安装windows+Ubuntu16.04双系统(上)
  • leetcode3265. 统计近似相等数对 I-medium
  • 编程技能:字符串函数07,strncat
  • C++跨平台开发经验与解决方案
  • Linux 文件(1)
  • 三维重建(二十三)——各种参数的测试(废案)
  • RV1126 + PCA9685实现7路舵机+2路减速电机控制
  • C++语法中的引用及其原理
  • 上位机知识篇---涂鸦智能云平台
  • Linux 线程(上)
  • Mamba LLM 架构简介:机器学习的新范式
  • SHAP分析图的含义
  • STM32F1软件调试详解
  • vLLM - LLM 类初始化参数
  • Addressable-加载指定资源
  • QT6 源(108)篇二:阅读与注释菜单栏里的菜单对象 QMenu,先是成员函数,后是信号函数的测试
  • Python 位运算:深入理解与实践应用
  • Linux开放访问端口
  • boost之signal2
  • 【ROS2】虚拟机使用fishros脚本一键安装humble