music.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // 导入ElMessage组件
  2. import { ElMessage } from 'element-plus';
  3. // 音乐类型配置(独立配置,不直接关联颜色)
  4. export const musicTypeConfig = {
  5. '平静': {
  6. url: '/src/assets/music/pingjing.mp3',
  7. name: '平静音乐'
  8. },
  9. '欢快': {
  10. url: '/src/assets/music/pingjing.mp3',
  11. name: '欢快音乐'
  12. },
  13. '舒缓': {
  14. url: '/src/assets/music/pingjing.mp3',
  15. name: '舒缓音乐'
  16. },
  17. '激情': {
  18. url: '/src/assets/music/pingjing.mp3',
  19. name: '激情音乐'
  20. },
  21. '冥想': {
  22. url: '/src/assets/music/pingjing.mp3',
  23. name: '冥想音乐'
  24. },
  25. '自然': {
  26. url: '/src/assets/music/pingjing.mp3',
  27. name: '自然音乐'
  28. }
  29. };
  30. // 播放音乐函数 - 修改为接受参数而不是直接使用外部变量
  31. export const playMusic = (musicType, state, musicPlayer) => {
  32. console.log(`尝试播放音乐类型: ${musicType}`);
  33. // 检查是否有对应的音乐配置
  34. if (musicTypeConfig[musicType]) {
  35. const musicInfo = musicTypeConfig[musicType];
  36. // 更新音乐播放状态
  37. state.currentMusicUrl = musicInfo.url;
  38. state.currentMusicName = musicInfo.name;
  39. // 延迟播放,确保audio元素已经更新了src
  40. setTimeout(() => {
  41. if (musicPlayer.value) {
  42. try {
  43. musicPlayer.value.play();
  44. state.isMusicPlaying = true;
  45. ElMessage.success(`正在播放: ${musicInfo.name}`);
  46. } catch (error) {
  47. console.error('播放音乐失败:', error);
  48. ElMessage.error('播放音乐失败,请稍后重试');
  49. }
  50. } else {
  51. console.error('音乐播放器元素未找到');
  52. ElMessage.error('音乐播放器初始化失败');
  53. }
  54. }, 100);
  55. } else {
  56. // 如果没有找到对应类型的音乐,使用默认音乐
  57. const defaultMusicType = '平静';
  58. const musicInfo = musicTypeConfig[defaultMusicType];
  59. state.currentMusicUrl = musicInfo.url;
  60. state.currentMusicName = musicInfo.name;
  61. setTimeout(() => {
  62. if (musicPlayer.value) {
  63. try {
  64. musicPlayer.value.play();
  65. state.isMusicPlaying = true;
  66. ElMessage.success(`正在播放默认音乐: ${musicInfo.name}`);
  67. } catch (error) {
  68. console.error('播放音乐失败:', error);
  69. ElMessage.error('播放音乐失败,请稍后重试');
  70. }
  71. } else {
  72. console.error('音乐播放器元素未找到');
  73. ElMessage.error('音乐播放器初始化失败');
  74. }
  75. }, 100);
  76. }
  77. };
  78. // 停止播放音乐 - 修改为接受参数
  79. export const stopMusic = (state, musicPlayer) => {
  80. if (musicPlayer.value) {
  81. musicPlayer.value.pause();
  82. // 重置播放进度
  83. musicPlayer.value.currentTime = 0;
  84. // 更新状态
  85. state.isMusicPlaying = false;
  86. state.currentMusicUrl = '';
  87. state.currentMusicName = '';
  88. console.log('音乐已停止播放');
  89. }
  90. };
  91. // 处理音乐播放结束事件
  92. export const onMusicEnded = (state) => {
  93. state.isMusicPlaying = false;
  94. state.currentMusicUrl = '';
  95. state.currentMusicName = '';
  96. console.log('音乐播放结束');
  97. };