0
点赞
收藏
分享

微信扫一扫

git基础-git别名

文章目录

1. react 倒计时 每秒播放一次音频简单demo代码

import React, { useState,useRef } from 'react';
import redBagMp3 from '@/branch/assets/mp3/redBag.mp3'
const DownTime = () => {
	const [timer, timerSet] = useState(5);
    const audioRef = useRef(null);//倒计时红包音频
    
	useEffect(() => {
	   // 第一秒播放
       if (timer > 0) playAudio()
        const countdownInterval = setInterval(() => {
            timerSet(prevValue => {
                const newValue = prevValue - 1;
                // 后面四秒播放
                if (newValue > 0) playAudio()
                if (newValue === 0) {
                    clearInterval(countdownInterval);
                }
                return newValue;
            });
        }, 1000);
    }, []);
	
	const playAudio = () => {
        if (audioRef.current) {
	        audioRef.current.play(); // 播放音频
        }
    };
    return (
        <div>
            <audio ref={audioRef}  src={redBagMp3} />
        </div >
    );
};

export default DownTime;

2. 问题及处理方式

2.1 Audio 引入出现的报错

Uncaught Error: Module parse failed: Unexpected character ‘’(1:3)

The above error occurred in one of your React components:
在这里插入图片描述

2.2 解决方法

这是因为项目中没有引入音频文件的 file-loader 导致的

  1. 安装 file-loader
cnpm i --save file-loader
  1. 在打包的 vite,或者webpack的配置里面添加 file-loader 配置,以下是已webpack位列,根据你的配置来
 module: {
     rules: [
         {
             test: /\.mp3$/,
             use: [
               {
                 loader: 'file-loader',
               },
             ],
         },
      ]
 }
举报

相关推荐

0 条评论