| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- // 导入ElMessage组件
- import { ElMessage } from 'element-plus';
- // 导入音乐文件 - 使用ES模块导入方式
- import huankuaiMp3 from '@/assets/music/huankuai.mp3';
- import shuhuanMp3 from '@/assets/music/shuhuan.mp3';
- // 音乐类型配置(独立配置,不直接关联颜色)
- export const musicTypeConfig = {
- '热闹': {
- url: huankuaiMp3, // 使用导入的变量
- name: '热闹音乐'
- },
- '舒缓': {
- url: shuhuanMp3, // 使用导入的变量
- name: '舒缓音乐'
- }
- };
- // 播放音乐函数 - 修改为接受参数而不是直接使用外部变量
- export const playMusic = (musicType, state, musicPlayer) => {
- console.log(`播放音乐类型: ${musicType}`);
- // 检查是否有对应的音乐配置
- if (musicTypeConfig[musicType]) {
- const musicInfo = musicTypeConfig[musicType];
- // 更新音乐播放状态
- state.currentMusicUrl = musicInfo.url;
- state.currentMusicName = musicInfo.name;
- // 延迟播放,确保audio元素已经更新了src
- setTimeout(() => {
- if (musicPlayer.value) {
- try {
- musicPlayer.value.play();
- state.isMusicPlaying = true;
- ElMessage.success(`正在播放: ${musicInfo.name}`);
- } catch (error) {
- console.error('播放音乐失败:', error);
- ElMessage.error('播放音乐失败,请稍后重试');
- }
- } else {
- console.error('音乐播放器元素未找到');
- ElMessage.error('音乐播放器初始化失败');
- }
- }, 100);
- } else {
- // 如果没有找到对应类型的音乐,使用默认音乐
- const defaultMusicType = '舒缓';
- const musicInfo = musicTypeConfig[defaultMusicType];
- state.currentMusicUrl = musicInfo.url;
- state.currentMusicName = musicInfo.name;
- setTimeout(() => {
- if (musicPlayer.value) {
- try {
- musicPlayer.value.play();
- state.isMusicPlaying = true;
- ElMessage.success(`正在播放默认音乐: ${musicInfo.name}`);
- } catch (error) {
- console.error('播放音乐失败:', error);
- ElMessage.error('播放音乐失败,请稍后重试');
- }
- } else {
- console.error('音乐播放器元素未找到');
- ElMessage.error('音乐播放器初始化失败');
- }
- }, 100);
- }
- };
- // 停止播放音乐 - 修改为接受参数
- export const stopMusic = (state, musicPlayer) => {
- if (musicPlayer.value) {
- musicPlayer.value.pause();
- // 重置播放进度
- musicPlayer.value.currentTime = 0;
- // 更新状态
- state.isMusicPlaying = false;
- state.currentMusicUrl = '';
- state.currentMusicName = '';
- console.log('音乐已停止播放');
- }
- };
- // 处理音乐播放结束事件
- export const onMusicEnded = (state) => {
- state.isMusicPlaying = false;
- state.currentMusicUrl = '';
- state.currentMusicName = '';
- console.log('音乐播放结束');
- };
- // 播放mp3文件
- export const playMp3 = async function(audioUrl) {
- if (!audioUrl) {
- console.error('音频URL为空');
- return;
- }
- try {
- // 创建音频对象,播放声音特效
- const soundEffect = new Audio(audioUrl);
- // 非阻塞方式播放音频
- soundEffect.play().catch(error => {
- console.error('播放声音特效失败:', error);
- });
- } catch (error) {
- console.error('创建声音特效失败:', error);
- }
- };
|