gpt4 book ai didi

javascript - 如何使用Hooks重新启动React Component中的音频

转载 作者:行者123 更新时间:2023-12-03 01:18:26 26 4
gpt4 key购买 nike

我正在尝试使用React制作音板。我从其他堆栈溢出答案中提取了一些代码,但是我无法工作的是在播放期间再次触发时重新启动音频。相反,它只是继续进行到最后。

这是我当前的代码:

import React, { useState, useEffect } from 'react'
import styled from 'styled-components'

const Button = (props) => {

const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);

const toggleSound = () => setPlaying(!playing);

useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing]
);

useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, []);

return [playing, toggleSound];
};

useEffect(() => {
function handleClick(e) {
if(e.key === props.trigger){
toggleSound();
}
}

window.addEventListener('keydown', handleClick);

return () => {
window.removeEventListener('keydown', handleClick);
};
}, []);

const [playing, toggleSound] = useAudio(`./sounds/${props.audio}`);

return (
<ButtonWrapper playing={playing} onClick={toggleSound}>
{props.children} - {props.trigger.toUpperCase()}
</ButtonWrapper>
)
}

export default Button;

const ButtonWrapper = styled.button`
background: ${props => props.playing ? 'red' : 'white'};
border: none;
font-size: 20px;
`

最佳答案

您是否尝试使用.load()方法?

该引用说.load()重新加载元素https://www.w3schools.com/tags/av_met_load.asp

关于javascript - 如何使用Hooks重新启动React Component中的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61807896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com