【发布时间】:2021-11-10 20:56:43
【问题描述】:
所以我正在尝试从 freeCodeCamp 构建 Drum Machine 项目,但我遇到了音频元素的这个问题。我写了下面的代码。我没有收到任何错误,但是当我单击带有“drum-pad”类的 div 时,音频仍然无法播放。我知道如何在没有 audio 元素的情况下完成这项工作,但挑战需要专门使用该元素。
我仍然会尝试自己解决这个问题,如果我在其他地方找到解决方案,我会更新这个问题。
这是我的 DrumPad 组件
import React from 'react';
class DrumPad extends React.Component {
constructor(props){
super(props);
this.state = {
name: this.props.name,
audio: this.props.source,
indexNr: this.props.indexNr,
keyId: this.props.keyId
}
this.clickHandle = this.clickHandle.bind(this);
this.keyPressHandle = this.keyPressHandle.bind(this);
}
clickHandle() {
document.getElementById(`audio${this.state.indexNr}`).play();
}
keyPressHandle(event) {
if(event.key === this.state.keyId || event.key === this.state.keyId.toLowerCase()){
document.getElementById(`audio${this.state.indexNr}`).play();
}
}
render(){
return (
<div className="drum-pad" id={this.name} onClick={this.clickHandle} onKeyPress={this.keyPressHandle}>
<h3>{this.state.keyId}</h3>
<audio id={`audio${this.state.indexNr}`} src={this.audio} />
</div>
)
}
}
export default DrumPad;
这是我的键盘组件
import DrumPad from "./DrumpPad";
const Keyboard = (props) => {
return <div className="column1">
{
soundsArr.map((sound, index) => <DrumPad key={index} indexNr={index} name={sound.name} source={sound.source} keyId={sound.keyId} />)
}
</div>
}
export default Keyboard;
const soundsArr = [
{
name: "Drum0",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "Q"
},
{
name: "Drum1",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "W"
},
{
name: "Drum2",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "E"
},
{
name: "Drum3",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "A"
},
{
name: "Drum4",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "S"
},
{
name: "Drum5",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "D"
},
{
name: "Drum6",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "Z"
},
{
name: "Drum7",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "X"
},
{
name: "Drum8",
source: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3",
keyId: "C"
}
];
【问题讨论】:
标签: javascript reactjs html5-audio