在 Vue 3 中,创建一个开箱即用的音频播放组件可以让你的应用程序快速集成音频播放功能。这个组件将基于原生的 <audio> 元素,并提供基本的播放、暂停、停止、音量控制以及进度条等功能。下面是创建这样一个组件的基本步骤和示例代码。

1. 创建组件

首先,你需要创建一个 Vue 3 组件,该组件将包含 <audio> 标签以及其他必要的元素,如按钮和进度条。

AudioPlayer.vue
<template>
  <div class="audio-player">
    <audio :src="audioSrc" ref="audioRef" @timeupdate="handleTimeUpdate" @ended="handleEnded"></audio>
    <button @click="togglePlay">{{ playText }}</button>
    <input type="range" min="0" max="100" :value="volume * 100" @change="setVolume" />
    <progress :value="currentTime" :max="duration"></progress>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

const audioSrc = 'https://example.com/path/to/audio.mp3';
const audioRef = ref(null);
const currentTime = ref(0);
const duration = ref(0);
const volume = ref(1);
const isPlaying = ref(false);

const playText = computed(() => isPlaying.value ? 'Pause' : 'Play');

function togglePlay() {
  if (isPlaying.value) {
    audioRef.value.pause();
  } else {
    audioRef.value.play();
  }
  isPlaying.value = !isPlaying.value;
}

function setVolume(event) {
  const newVolume = event.target.value / 100;
  audioRef.value.volume = newVolume;
  volume.value = newVolume;
}

function handleTimeUpdate() {
  currentTime.value = audioRef.value.currentTime;
  if (audioRef.value.duration > 0) {
    duration.value = audioRef.value.duration;
  }
}

function handleEnded() {
  isPlaying.value = false;
  currentTime.value = 0;
}

onMounted(() => {
  audioRef.value.addEventListener('canplay', () => {
    duration.value = audioRef.value.duration;
  });
});
</script>

<style scoped>
.audio-player {
  display: flex;
  flex-direction: column;
  align-items: center;
}
progress[value] {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 20px;
  background-color: #ddd;
}
progress[value]::-webkit-progress-bar {
  background-color: #ddd;
}
progress[value]::-webkit-progress-value {
  background-color: blue;
}
</style>

2. 使用组件

接下来,你可以在你的应用程序中使用这个组件。例如,在一个页面中引入并使用这个组件:

YourPage.vue
<template>
  <div>
    <h1>Your Audio Player</h1>
    <AudioPlayer />
  </div>
</template>

<script setup>
import AudioPlayer from '@/components/AudioPlayer.vue';
</script>

3. 说明

  • 模板部分:定义了播放按钮、音量滑块和进度条。<audio> 元素用于播放音频,并绑定了 ref 以方便在脚本中操作。
  • 脚本部分:使用了 Vue 3 的 Composition API 来管理组件的状态和行为。onMounted 钩子确保在组件挂载后添加事件监听器。
  • 样式部分:提供了基本的样式来美化进度条。

4. 扩展功能

这个基本的音频播放组件可以根据需要扩展更多功能,比如:

  • 播放列表:支持多个音频文件的选择和播放。
  • 循环播放:允许用户设置音频是否循环播放。
  • 进度拖动:允许用户通过拖动进度条来跳转到音频的任意位置。
  • 播放速度控制:让用户可以调节音频播放的速度。

5. 测试和调试

在开发过程中,记得测试组件在不同设备和浏览器中的表现,并根据需要调整样式和逻辑。确保组件的用户体验良好,并且在不同的网络条件下也能稳定工作。