Keydown使用React播放音频



我正在为FreeCodeCamp制作一台鼓机,但当点击特定键时,我很难播放音频。我最近的尝试可以在handleKeyDown中看到。该函数正在接收事件,我可以呈现哪个键被击中,但不确定如何播放src。我不知道如何使if语句工作,也不知道if语句中的代码。我删除了一些我认为与问题无关的代码。我应该如何处理?非常感谢。

const sounds = [
{
key: 'Q',
keyCode: 81,
id: 'Heater-1',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
},
{
key: 'W',
keyCode: 87,
id: 'Heater-2',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
}
];
class App extends React.Component {
constructor(props) {
super(props);
this.audio = React.createRef()
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeydown);
}
componenetWillUnmount() {
document.removeEventListener('keydown', this.handleKeydown);
}

handleKeydown = (e) => {
if (e.keyCode === this.props.keyCode) {

const audio = document.getElementById(this.props.key);
audio.currentTime = 0;
audio.play();
}
}


render() {
return (
<div id="drum-machine">
<div id="drumpad">
{sounds.map(i => (
<button
className="drum-pad"
id={i.key}
key={i.key}
onClick={this.handleClick}
value={i.key}
>{i.key}
<audio 
className="clip" 
id={i.key}
src={i.url}
ref={this.audio}
/></button>
))}
</div>
</div>
);
}
}
//file for export, comm.js
export const AudioPlay = (file) => {
new Audio(`/static/sounds/${file}`).play();    //under folder public
};
//file import
import {AudioPlay} from './comm';
//in your event function
AudioPlay('stockin-ok.mp3');

最新更新