audio
const AudioCom = () => {
const audioRef = useRef<any>();
const [isPlay, setIsPlay] = useState(false);
const listenCanPlayAudio = () => {
if (audioRef.current) {
audioRef.current.addEventListener('canplay', () => {
audioRef.current.play();
});
}
};
const playMusic = () => {
if (audioRef.current) {
audioRef.current.play();
try {
const windowObj = window.windowObj || {};
if (windowObj.wx) {
windowObj.wx.ready(() => {
audioRef.current.play();
});
}
} catch (error) {}
}
};
const pauseMusic = () => {
if (audioRef.current) {
audioRef.current.pause();
}
};
const listenMusicPlayStatus = () => {
if (audioRef.current) {
audioRef.current.addEventListener('play', () => {
setIsPlay(true);
});
audioRef.current.addEventListener('pause', () => {
setIsPlay(false);
});
}
};
const clickMusicIcon = () => {
if (isPlay) {
pauseMusic();
} else {
playMusic();
}
};
useEffect(() => {
listenCanPlayAudio();
listenMusicPlayStatus();
}, []);
return (<div>
<div
onClick={() => {clickMusicIcon();}}
className={isPlay ? styles.bgm : styles.bgmc}
></div>
<audio className={styles.audio} ref={audioRef} loop preload="preload" src={BGMUrl}></audio>
</div>)
}
export default AudioCom
video
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import videoUrl from 'src/assets/video.mp4';
const Loading = ({ onLoaded }) => {
const loaddingRef = useRef<any>(null);
const endedCallbackRef = useRef<any>(null);
const [isOver, setIsOver] = useState(false);
const timer = useRef<any>();
useEffect(() => {
const onCallback = () => {
endedCallbackRef?.current?.();
setIsOver(true);
};
if (loaddingRef?.current && loaddingRef?.current?.addEventListener) {
loaddingRef?.current?.addEventListener?.('ended', onCallback);
}
return () => {
loaddingRef?.current?.removeEventListener?.('ended', onCallback);
};
}, []);
useEffect(() => {
setIsOver(false);
endedCallbackRef.current = onLoaded;
loaddingRef.current.currentTime = 0;
loaddingRef.current.play();
timer.current = setTimeout(() => {
console.log('倒计时2S 播放结束');
setIsOver(true);
onLoaded();
}, 2000);
return () => {
clearTimeout(timer.current);
};
}, [onLoaded]);
useEffect(() => {
loaddingRef.current.currentTime = 0;
loaddingRef.current.play();
}, []);
return (
<div className="screenBox-loading" style={{ zIndex: `${isOver ? -1 : 99}` }}>
<video
className="screenBoxVideo"
style={{ zIndex: `${isOver ? -1 : 99}` }}
ref={loaddingRef}
muted
loop={false}
playsInline
poster={videoUrl}
>
<source src={videoUrl} type="video/mp4" />
</video>
</div>
);
};
export default Loading;