本文主要是介绍react Audio 倒计时5秒,每秒播放一次音频,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 1. react 倒计时 每秒播放一次音频简单demo代码
- 2. 问题及处理方式
- 2.1 Audio 引入出现的报错
- 2.2 解决方法
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
导致的
- 安装 file-loader
cnpm i --save file-loader
- 在打包的
vite
,或者webpack
的配置里面添加file-loader
配置,以下是已webpack位列,根据你的配置来
module: {rules: [{test: /\.mp3$/,use: [{loader: 'file-loader',},],},]}
这篇关于react Audio 倒计时5秒,每秒播放一次音频的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!