切换播放/暂停按钮在下一步与mp3音频



我正在建设我的网站,我想在我的页面底部的按钮,这将使用useSound播放/暂停一首歌。当我第一次点击的时候,它就开始播放了,但是我不能让我的歌停下来。

谁能给我指个正确的方向?请看下面我的代码

import useSound from 'use-sound';
import galaxySfx from '../../public/sounds/galaxy.mp3';
import styles from "./sound.module.scss";
import Aos from "aos";
import "aos/dist/aos.css";
const PlayButton = ({}) => {
const [play, { stop, isPlaying }] = useSound(galaxySfx);
function playSong() {
isPlaying === true;
play(); 
}
function stopSong() {
isPlaying === false;
stop();
}

return (
<div className={styles.playButton}>
<button 
data-aos="zoom-in"
data-aos-offset="100"
onClick={isPlaying ? stopSong() : playSong()}
>
🎺
</button>
</div>
);
};
export default PlayButton;

在阅读了use-sound documentation之后,我没有从您正在解构的第二个返回值中看到任何isPlaying值。

所以isPlaying将是未定义的,但是你可以用useState来跟踪播放状态。

...
import { useState } from "react";
const PlayButton = ({}) => {
const [isPlaying, setIsPlaying] = useState(false);
const [play, { stop }] = useSound(galaxySfx);
function playSong() {
setIsPlaying(true);
play();
}
function stopSong() {
setIsPlaying(false);
stop();
}

onClickprop期望一个函数被调用,所以你不应该调用你传递给它的任何函数。

return (
<div className={styles.playButton}>
<button
data-aos="zoom-in"
data-aos-offset="100"
onClick={isPlaying ? stopSong : playSong}
>
🎺
</button>
</div>
);
}

您可以为这两个操作使用相同的处理程序。检查isPlaying变量的状态并采取相应的行动:

function togglePlay(){
if(isPlaying){
stop();
} else{
play();
}
}

只要去掉括号,这样函数就不会运行,除非你onClick

onClick={isPlaying ? stop: play}

相关内容

最新更新