播放视频带同步音波功能
Wavesurfer.js
官网地址
wavesurfer.js是一个用于在Web浏览器中实时可视化音频波形的JavaScript库
支持多种音频文件格式,包括MP3、WAV、AAC和Ogg等,
并且可以通过调用相应的加载方法加载任何支持的音频文件
支持播放、暂停、跳转、缩放、选择和剪切等操作
允许用户自定义波形的外观和样式,包括颜色、阴影效果、进度条和标记
npm install wavesurfer.js --save
<template><div><div ref="waveform"></div><video ref="video"controls playsinline style="width: 100%; max-width: 600px; margin: 0 auto; display: block;"><source :src="audioSrc" type="video/mp4">Your browser does not support the video tag.</video></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import WaveSurfer from 'wavesurfer.js';
// Data
const waveform = ref(null);
const video = ref(null);
const audioSrc = new URL('../src/audio/11.mp4', import.meta.url).href;
let wavesurfer = null;
// Methods
const initWaveform = () => {wavesurfer = WaveSurfer.create({height:28, // 设置波形的高度container: waveform.value,waveColor: 'rgb(200, 0, 200)',progressColor: 'rgb(100, 0, 100)',cursorColor: 'black',backend: 'MediaElement', // 使用 MediaElement 后端来支持视频元素mediaControls: true, // 如果您希望 WaveSurfer 控制媒体控件,请设为 truemedia: video.value, // 直接传递视频元素});// 监听 ready 事件确保 WaveSurfer 已经准备好wavesurfer.on('ready', () => {console.log('WaveSurfer is ready');});// 设置同步逻辑const syncVideoAndWaveSurfer = () => {video.value.addEventListener('play', () => wavesurfer.play());video.value.addEventListener('pause', () => wavesurfer.pause());video.value.addEventListener('seeked', () => wavesurfer.seekTo(video.value.currentTime / video.value.duration));wavesurfer.on('seek', (pos) => {video.value.currentTime = pos * video.value.duration;});wavesurfer.on('finish', () => {video.value.pause();video.value.currentTime = 0; // 可选:回到视频开始位置});};// 确保视频已经加载元数据后再进行同步watch(() => video.value.readyState, (newVal) => {if (newVal >= 2 && wavesurfer.isReady) {syncVideoAndWaveSurfer();}}, { immediate: true });wavesurfer.load(audioSrc); // 加载音频文件
};// Lifecycle hooks
onMounted(() => {initWaveform();
});onBeforeUnmount(() => {if (wavesurfer) {wavesurfer.destroy(); // 清理 WaveSurfer 实例}// 移除所有事件监听器以防止内存泄漏if (video.value) {video.value.removeEventListener('play', wavesurfer.play.bind(wavesurfer));video.value.removeEventListener('pause', wavesurfer.pause.bind(wavesurfer));video.value.removeEventListener('seeked', wavesurfer.seekTo.bind(wavesurfer));}
});
</script><style scoped>
/* 在这里添加样式 */
</style>