import { defineComponent, onMounted, toRefs, reactive } from 'vue'; import styles from './audio.module.less'; import WaveSurfer from 'wavesurfer.js'; import iconplay from '../image/icon-pause.svg'; import iconpause from '../image/icon-play.svg'; import { NSlider } from 'naive-ui'; export default defineComponent({ name: 'audio-play', props: { item: { type: Object, default: () => { return {}; } }, isEmtry: { type: Boolean, default: false } }, setup(props) { const { item } = toRefs(props); const audioId = 'a' + +Date.now() + Math.floor(Math.random() * 100); const audioForms = reactive({ paused: true, currentTimeNum: 0, currentTime: '00:00', duration: '00:00' }); const audioDom = new Audio(); audioDom.controls = true; audioDom.style.width = '100%'; audioDom.className = styles.audio; document.querySelector(`#${audioId}`)?.appendChild(audioDom); onMounted(() => { const wavesurfer = WaveSurfer.create({ container: document.querySelector(`#${audioId}`) as HTMLElement, waveColor: '#C5C5C5', progressColor: '#02baff', url: item.value.content + '?t=' + +new Date(), cursorWidth: 0, height: 160, normalize: true, // Set a bar width barWidth: 6, // Optionally, specify the spacing between bars barGap: 12, // And the bar radius barRadius: 12, autoScroll: true, /** If autoScroll is enabled, keep the cursor in the center of the waveform during playback */ autoCenter: true, hideScrollbar: false, media: audioDom }); wavesurfer.once('interaction', () => { // wavesurfer.play(); }); wavesurfer.once('ready', () => { audioForms.paused = audioDom.paused; audioForms.duration = timeFormat(Math.round(audioDom.duration)); }); wavesurfer.on('finish', () => { audioForms.paused = true; }); }); // 切换音频播放 const onToggleAudio = (e: MouseEvent) => { e.stopPropagation(); if (audioDom.paused) { audioDom.play(); } else { audioDom.pause(); } audioForms.paused = audioDom.paused; }; // 播放时监听 audioDom.addEventListener('timeupdate', () => { audioForms.currentTime = timeFormat(Math.round(audioDom.currentTime)); audioForms.currentTimeNum = audioDom.currentTime; }); // 播放结束时 // 对时间进行格式化 const timeFormat = (num: number) => { if (num > 0) { const m = Math.floor(num / 60); const s = num % 60; return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s); } else { return '00:00'; } }; return () => (
{ e.stopPropagation(); }}>
{ e.stopPropagation(); }}>
{audioForms.currentTime}
/
{audioForms.duration}
); } });