AudioPlayer.vue 16.3 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
<!--
 * @Date: 2025-04-07 12:35:35
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-06-11 11:58:22
 * @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-2">
    <!-- 封面与歌曲信息 -->
    <div class="flex flex-col items-center mb-4">
      <!-- 歌曲封面 -->
      <div class="w-24 h-24 rounded-lg overflow-hidden mb-2">
        <img :src="currentSong?.cover ? currentSong?.cover : 'https://cdn.ipadbiz.cn/mlaj/images/audio_d_cover.jpg'" alt="封面" class="w-full h-full object-cover">
      </div>

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

    </div>

      <!-- 进度条与时间:显示当前播放时间、总时长和可拖动的进度条 -->
      <div class="mt-4 mb-6">
        <div class="flex items-center space-x-4">
          <span class="text-xs text-gray-400 w-12 text-right">{{ formatTime(currentTime) }}</span>
          <div class="progress-bar relative h-1 bg-gray-200 rounded-full flex-1">
            <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>
          <span class="text-xs text-gray-400 w-12">{{ formatTime(duration) }}</span>
        </div>
      </div>

      <!-- 播放控制按钮组:上一首、播放/暂停、下一首 -->
      <div class="flex items-center space-x-12 mt-4" style="justify-content: space-evenly;">
        <button
          @click="prevSong"
          class="w-10 h-10 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
        >
          <font-awesome-icon icon="backward-step" class="text-xl text-gray-600" />
        </button>
        <button
          @click="togglePlay"
          :class="{'paused': !isPlaying, 'opacity-50 cursor-not-allowed': isLoading}"
          :disabled="isLoading"
          class="w-12 h-12 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-10 h-10 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
        >
          <font-awesome-icon icon="forward-step" class="text-xl 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 ? song?.cover : 'https://cdn.ipadbiz.cn/mlaj/images/audio_d_cover.jpg'" 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 && isPlaying"
            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({
  id: { type: String }, // 组件ID
  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) {
    console.warn('没有可播放的歌曲')
    return false
  }

  // 设置加载状态
  isLoading.value = true

  try {
    // 清理旧的音频实例
    if (audio.value) {
      audio.value.removeEventListener('timeupdate', updateProgress)
      audio.value.removeEventListener('ended', handleEnded)
    }

    // 检查歌曲URL是否存在
    if (!currentSong.value.url) {
      console.error('歌曲URL不存在:', currentSong.value)
      audio.value = null
      return false
    }

    // 创建新的音频实例
    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()
    return new Promise((resolve) => {
      audio.value.addEventListener('canplaythrough', () => {
        resolve(true)
      }, { once: true })
      audio.value.addEventListener('error', () => {
        console.error('音频加载失败')
        resolve(false)
      }, { once: true })
    })
  } catch (error) {
    console.error('加载音频失败:', error)
    audio.value = null
    return false
  } finally {
    isLoading.value = false
  }
}

// 定义组件事件
const emit = defineEmits(['play', 'pause'])

// 播放控制:切换播放/暂停状态
const togglePlay = async () => {
  // 如果正在加载中,不执行任何操作
  if (isLoading.value) return

  try {
    // 如果音频实例不存在,尝试加载
    if (!audio.value) {
      const loadSuccess = await loadAudio()
      // 如果加载失败,直接返回
      if (!loadSuccess || !audio.value) {
        console.warn('无法加载音频实例')
        return
      }
    }

    // 根据当前播放状态执行相应操作
    if (isPlaying.value) {
      // 暂停播放
      if (audio.value) {
        await audio.value.pause()
        emit('pause', audio.value)
      }
    } else {
      // 开始播放
      if (audio.value) {
        try {
          await audio.value.play()
          emit('play', audio.value)
        } catch (playError) {
          console.error('播放失败:', playError)
          return
        }
      }
    }

    // 切换播放状态
    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 () => {
  try {
    // 如果音频实例存在,先暂停并清除
    if (audio.value) {
      isPlaying.value = false
      await audio.value.pause()
      audio.value = null
    }

    // 计算上一首歌曲的索引
    currentIndex.value = (currentIndex.value - 1 + props.songs.length) % props.songs.length

    // 加载新的音频
    const loadSuccess = await loadAudio()

    // 确保音频实例加载成功后再播放
    if (loadSuccess && audio.value) {
      try {
        await audio.value.play()
        // 使用非线性映射来调整音量变化的灵敏度
        const normalizedVolume = Math.pow(volume.value / 100, 2)
        audio.value.volume = normalizedVolume
        isPlaying.value = true
        // 发射播放事件
        emit('play', audio.value)
      } catch (playError) {
        console.error('播放上一首歌曲失败:', playError)
        isPlaying.value = false
      }
    } else {
      console.warn('无法加载上一首歌曲')
      isPlaying.value = false
    }
  } catch (error) {
    console.error('切换到上一首歌曲失败:', error)
    isPlaying.value = false
  }
}

// 控制方法:切换到下一首
const nextSong = async () => {
  try {
    // 如果音频实例存在,先暂停并清除
    if (audio.value) {
      isPlaying.value = false
      await audio.value.pause()
      audio.value = null
    }

    // 计算下一首歌曲的索引
    currentIndex.value = (currentIndex.value + 1) % props.songs.length

    // 加载新的音频
    const loadSuccess = await loadAudio()

    // 确保音频实例加载成功后再播放
    if (loadSuccess && audio.value) {
      try {
        await audio.value.play()
        // 使用非线性映射来调整音量变化的灵敏度
        const normalizedVolume = Math.pow(volume.value / 100, 2)
        audio.value.volume = normalizedVolume
        isPlaying.value = true
        // 发射播放事件
        emit('play', audio.value)
      } catch (playError) {
        console.error('播放下一首歌曲失败:', playError)
        isPlaying.value = false
      }
    } else {
      console.warn('无法加载下一首歌曲')
      isPlaying.value = false
    }
  } catch (error) {
    console.error('切换到下一首歌曲失败:', error)
    isPlaying.value = false
  }
}

// 重新播放当前歌曲
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, () => {
  console.warn('歌曲列表变化', props.songs);
  currentIndex.value = 0
  loadAudio()
}, { deep: true })

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

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

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

// 选择并播放指定歌曲
const selectSong = async (index) => {
  try {
    // 如果音频实例存在,先暂停并清除
    if (audio.value) {
      isPlaying.value = false
      await audio.value.pause()
      audio.value = null
    }

    // 设置当前索引
    currentIndex.value = index

    // 加载新的音频
    const loadSuccess = await loadAudio()

    // 确保音频实例加载成功后再播放
    if (loadSuccess && audio.value) {
      console.warn('正在播放选择的歌曲', audio.value);
      try {
        await audio.value.play()
        isPlaying.value = true
        // 发射播放事件
        emit('play', audio.value)
        // 关闭播放列表
        isPlaylistVisible.value = false
        // 滚动到当前播放的音频
        const playlistItems = document.querySelector('.playlist-items')
        const activeItem = playlistItems?.querySelector('.active')
        if (playlistItems && activeItem) {
          activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
        }
      } catch (playError) {
        console.error('播放选择的歌曲失败:', playError)
        isPlaying.value = false
      }
    } else {
      console.warn('无法加载选择的歌曲')
      isPlaying.value = false
    }
  } catch (error) {
    console.error('选择歌曲失败:', error)
    isPlaying.value = false
  }
}

// 监听播放状态变化,确保当前播放项在可视区域内
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' })
    }
  }
})


// 暴露给父组件的方法
defineExpose({
  togglePlay,
  pause: () => {
    // 只有在播放状态且音频实例存在时才执行暂停
    if (isPlaying.value && audio.value) {
      audio.value.pause();
      isPlaying.value = false;
      emit('pause', audio.value);
    } else {
      // 如果音频实例不存在或已经暂停,只更新状态
      isPlaying.value = false;
    }
  },
  isPlaying: () => isPlaying.value,
  id: props.id,
  getPlayer: () => audio.value,
  getId() {
    return currentSong.value.meta_id || 'meta_id'
  }
})
</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>