Reputation: 570
I am trying to play different sound with each button. And I try to access the sound url from array variable with passed index number
I pass index number with key in playSound function then I try to get url from const piano variable it throws an error in console. what I am doing wrong here ?
let { Button, ButtonToolbar, ButtonGroup, Radio, DropdownButton, MenuItem } = ReactBootstrap;
class App extends React.Component {
constructor(props){
super(props);
this.state = {
power: true,
instrument: 'piano',
buttonColor:true,
};
this.playSound = this.playSound.bind(this);
this.toggle = this.toggle.bind(this);
this.changeColor =this.changeColor.bind(this);
const piano = [{
keyCode: 81,
keyTrigger: 'Q',
id: 'Heater-1',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
}, {
keyCode: 87,
keyTrigger: 'W',
id: 'Heater-2',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
}, {
keyCode: 69,
keyTrigger: 'E',
id: 'Heater-3',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3'
},
];
changeColor(){
this.setState({buttonColor: !this.state.buttonColor})
}
playSound(key){
if (this.state.power == true) {
this.audio = new Audio(this.piano[key].url)
this.audio.play();
this.changeColor();
setTimeout(() => this.changeColor(), 200 )
}
};
toggle() {
this.setState({
power: !this.state.power,
});
console.log(!this.state.power)
};
render(){
let btn_style = this.state.buttonColor ? 'primary' : 'warning'
return(
<div id='container' >
<div className='buttons' >
<div className='firstLine'>
<ButtonToolbar>
<Button bsStyle= {btn_style} className='drum-pad' bsSize="large" onClick = {() => this.playSound(0)} >Q</Button>
<Button bsStyle= {btn_style} className='drum-pad' bsSize="large" onClick = {() => this.playSound(1)} >W</Button>
<Button bsStyle="primary" className='drum-pad' bsSize="large">E</Button>
</ButtonToolbar>
</div>
</div>
</div>
)
}
}
Upvotes: 0
Views: 2168
Reputation: 2523
I guess you have missed the ending }
of constructor after piano
.
You cannot declare a const variable in the constructor to use it later by accessing it like this.piano
. To know more about that check out this SO Answer.
So, declare it like a variable like you did for state
.
Just change your const piano = [];
to this.piano = [];
.
It should work.
Upvotes: 2