AudioPlayer.vue 11.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
<!--
 * @Date: 2025-04-07 12:35:35
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-04-07 17:37:34
 * @FilePath: /mlaj/src/components/ui/audioPlayer.vue
 * @Description: 音频播放器组件,支持播放控制、进度条调节、音量控制、播放列表等功能
-->
<template>
  <!-- 音频播放器主容器 -->
  <div class="audio-player bg-white rounded-lg shadow-xl overflow-hidden max-w-md mx-auto p-4">
    <!-- 封面与歌曲信息 -->
    <div class="flex flex-col items-center mb-6">
      <!-- 歌曲封面 -->
      <div class="w-48 h-48 rounded-lg overflow-hidden mb-4">
        <img :src="currentSong.cover" alt="封面" class="w-full h-full object-cover">
      </div>

      <!-- 歌曲信息 -->
      <div class="text-center">
        <h3 class="text-lg font-medium">{{ currentSong.title }}</h3>
        <p class="text-sm text-gray-500">{{ currentSong.artist }}</p>
      </div>

      </div>

      <!-- 进度条与时间:显示当前播放时间、总时长和可拖动的进度条 -->
      <div class="mt-4 mb-6">
        <div class="flex items-center justify-between text-xs text-gray-400 mb-2">
          <span>{{ formatTime(currentTime) }}</span>
          <span>{{ formatTime(duration) }}</span>
        </div>
        <div class="progress-bar relative h-1 bg-gray-200 rounded-full">
          <input
            type="range"
            :value="progress"
            @input="handleProgressChange"
            @change="seekTo"
            class="w-full absolute inset-0 appearance-none bg-transparent cursor-pointer"
          >
          <div
            :style="{ width: `${progress}%` }"
            class="progress-track absolute left-0 top-0 h-full rounded-full bg-gradient-to-r from-blue-500 to-purple-500 transition-all"
          ></div>
        </div>
      </div>

      <!-- 播放控制按钮组:上一首、播放/暂停、下一首 -->
      <div class="flex items-center space-x-16 mt-6" style="justify-content: space-evenly;">
        <button
          @click="prevSong"
          class="w-14 h-14 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
        >
          <font-awesome-icon icon="backward-step" class="text-2xl text-gray-600" />
        </button>
        <button
          @click="togglePlay"
          :class="{'paused': !isPlaying, 'opacity-50 cursor-not-allowed': isLoading}"
          :disabled="isLoading"
          class="w-14 h-14 flex items-center justify-center rounded-full bg-blue-500 hover:bg-blue-600 transition-colors shadow-lg"
        >
          <font-awesome-icon
            :icon="['fas' , isPlaying ? 'pause' : 'play']"
            :class="{ 'fa-spin': isLoading }"
            class="text-2xl"
          />
        </button>
        <button
          @click="nextSong"
          class="w-14 h-14 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
        >
          <font-awesome-icon icon="forward-step" class="text-2xl text-gray-600" />
        </button>
      </div>

    <!-- 播放列表按钮 -->
    <div class="flex justify-end mt-4">
      <button @click="togglePlaylist" class="text-gray-500 hover:text-gray-700 transition-colors">
        <font-awesome-icon icon="list" class="text-lg" />
      </button>
    </div>

    <!-- 播放列表弹出层 -->
    <van-popup
      teleport="body"
      v-model:show="isPlaylistVisible"
      position="bottom"
      :overlay="true"
      round
      class="playlist-popup"
      style="height: 70vh"
    >
      <div class="playlist-header flex justify-between items-center px-4 py-3 border-b sticky top-0 bg-white z-10">
        <h4 class="font-medium">播放列表 ({{ songs.length }})</h4>
        <button @click="closePlaylist" class="text-gray-500 hover:text-gray-700 transition-colors">
          <font-awesome-icon icon="xmark" />
        </button>
      </div>
      <div class="playlist-items overflow-y-auto h-full pb-safe">
        <div
          v-for="(song, index) in songs"
          :key="song.id"
          :class="{'active bg-blue-50': index === currentIndex}"
          @click="selectSong(index)"
          class="flex items-center px-4 py-3 hover:bg-gray-50 transition-colors relative"
        >
          <div class="absolute top-0 left-0 right-0 h-[1px] bg-gray-200"></div>
          <div class="w-16 h-16 rounded-lg overflow-hidden mr-4 flex-shrink-0">
            <img :src="song.cover" alt="封面" class="w-full h-full object-cover">
          </div>
          <div class="flex-1">
            <div class="font-medium">{{ song.title }}</div>
            <div class="text-sm text-gray-500">{{ song.artist }}</div>
          </div>
          <font-awesome-icon
            v-if="index === currentIndex"
            icon="volume-up"
            class="text-blue-500 ml-2"
          />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { formatTime } from '@/utils/time'
import { wxInfo } from '@/utils/tools'

// 组件属性定义
const props = defineProps({
  songs: { type: Array, required: true }, // 音频列表数据
  initialIndex: { type: Number, default: 0 } // 初始播放索引
})

// 音频播放器状态管理
const audio = ref(null) // 音频实例
const isPlaying = ref(false) // 播放状态
const isLoading = ref(false) // 加载状态
const currentIndex = ref(props.initialIndex) // 当前播放索引
const currentTime = ref(0) // 当前播放时间
const duration = ref(0) // 音频总时长
const progress = ref(0) // 播放进度
const volume = ref(100) // 音量值
const isPlaylistVisible = ref(false) // 播放列表显示状态
const speed = ref(1.0) // 播放速度

// 计算属性
const currentSong = computed(() => props.songs[currentIndex.value]) // 当前播放的歌曲

// 生命周期钩子
onMounted(() => {
  loadAudio()
  audio.value?.addEventListener('timeupdate', updateProgress)
  audio.value?.addEventListener('ended', handleEnded)
})

// 核心方法:音频加载
const loadAudio = async () => {
  if (!currentSong.value) return
  isLoading.value = true
  try {
    if (audio.value) {
      audio.value.removeEventListener('timeupdate', updateProgress)
      audio.value.removeEventListener('ended', handleEnded)
    }
    audio.value = new Audio(currentSong.value.url)
    audio.value.volume = volume.value / 100
    audio.value.playbackRate = speed.value
    audio.value.addEventListener('timeupdate', updateProgress)
    audio.value.addEventListener('ended', handleEnded)
    await audio.value.load()
  } catch (error) {
    console.error('加载音频失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 播放控制:切换播放/暂停状态
const togglePlay = async () => {
  if (isLoading.value) return
  try {
    if (!audio.value) {
      await loadAudio()
    }
    if (isPlaying.value) {
      await audio.value?.pause()
    } else {
      await audio.value?.play()
    }
    isPlaying.value = !isPlaying.value
  } catch (error) {
    console.error('播放控制失败:', error)
  }
}

// 进度更新
const updateProgress = () => {
  if (!audio.value) return
  currentTime.value = audio.value.currentTime
  duration.value = audio.value.duration
  progress.value = (currentTime.value / duration.value) * 100 || 0
}

// 播放结束处理
const handleEnded = () => {
  nextSong()
}

// 控制方法:切换到上一首
const prevSong = async () => {
  if (audio.value) {
    isPlaying.value = false
    await audio.value.pause()
    audio.value = null
  }
  currentIndex.value = (currentIndex.value - 1 + props.songs.length) % props.songs.length
  await loadAudio()
  if (audio.value) {
    await audio.value.play()
    // 使用非线性映射来调整音量变化的灵敏度
    const normalizedVolume = Math.pow(volume.value / 100, 2)
    audio.value.volume = normalizedVolume
    isPlaying.value = true
  }
}

// 控制方法:切换到下一首
const nextSong = async () => {
  if (audio.value) {
    isPlaying.value = false
    await audio.value.pause()
    audio.value = null
  }
  currentIndex.value = (currentIndex.value + 1) % props.songs.length
  await loadAudio()
  if (audio.value) {
    await audio.value.play()
    // 使用非线性映射来调整音量变化的灵敏度
    const normalizedVolume = Math.pow(volume.value / 100, 2)
    audio.value.volume = normalizedVolume
    isPlaying.value = true
  }
}

// 重新播放当前歌曲
const replaySong = () => {
  audio.value?.seek(0)
  togglePlay()
}

// 进度条交互处理
const handleProgressChange = (e) => {
  const target = e.target
  progress.value = parseFloat(target.value)
}

// 跳转到指定进度
const seekTo = () => {
  if (!audio.value || !duration.value) return
  audio.value.currentTime = (progress.value / 100) * duration.value
}

// 音量控制处理
const handleVolumeChange = (e) => {
  const target = e.target
  volume.value = parseFloat(target.value)
  // 使用非线性映射来调整音量变化的灵敏度
  const normalizedVolume = Math.pow(volume.value / 100, 2)
  if (audio.value) {
    audio.value.volume = normalizedVolume
  }
}

// 监听歌曲列表变化
watch(() => props.songs, () => {
  currentIndex.value = 0
  loadAudio()
}, { deep: true })

// 组件卸载时清理事件监听
onUnmounted(() => {
  audio.value?.removeEventListener('timeupdate', updateProgress)
  audio.value?.removeEventListener('ended', handleEnded)
})

// 播放列表相关方法
const togglePlaylist = () => {
  isPlaylistVisible.value = !isPlaylistVisible.value
}

const closePlaylist = () => {
  isPlaylistVisible.value = false
}

// 选择并播放指定歌曲
const selectSong = async (index) => {
  if (audio.value) {
    isPlaying.value = false
    await audio.value.pause()
    audio.value = null
  }
  currentIndex.value = index
  await loadAudio()
  if (audio.value) {
    await audio.value.play()
    isPlaying.value = true
    // 关闭播放列表
    isPlaylistVisible.value = false
    // 滚动到当前播放的音频
    const playlistItems = document.querySelector('.playlist-items')
    const activeItem = playlistItems?.querySelector('.active')
    if (playlistItems && activeItem) {
      activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
    }
  }
}

// 监听播放状态变化,确保当前播放项在可视区域内
watch([isPlaying, currentIndex], () => {
  if (isPlaying.value) {
    const playlistItems = document.querySelector('.playlist-items')
    const activeItem = playlistItems?.querySelector('.active')
    if (playlistItems && activeItem) {
      activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
    }
  }
})
</script>

<style scoped>
/* 音频播放器样式变量 */
.audio-player {
  --progress-height: 4px;
}

/* 进度条样式 */
.progress-bar {
  height: var(--progress-height);
  border-radius: var(--progress-height);
}

.progress-track {
  height: var(--progress-height);
  border-radius: var(--progress-height);
  background: linear-gradient(90deg, #1a1a1a 0%, #4a4a4a 100%);
  transition: width 0.3s ease-in-out;
}

input[type='range'] {
  -webkit-appearance: none;
  appearance: none;
  background: transparent;
}

input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 0;
  height: 0;
}

input[type='range']::-moz-range-thumb {
  width: 0;
  height: 0;
  border: 0;
}

/* 按钮交互动画 */
button:not(:disabled) {
  transition: all 0.3s ease;
}

@media (hover: hover) {
  button:not(:disabled):hover {
    transform: scale(1.1);
  }
}

button.paused .fa-pause {
  animation: pulse 1.5s infinite;
}

button:disabled {
  cursor: not-allowed;
}

/* 暂停按钮动画 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 播放列表样式 */


.active {
  background-color: #f3f4f6;
  font-weight: 500;
  color: #1a1a1a;
}

/* 移动端样式优化 */
@media (max-width: 640px) {
  .audio-player {
    --progress-height: 6px;
  }

  input[type="range"] {
    height: var(--progress-height);
  }
}
</style>