Tell us what’s happening: I’m having trouble getting my code to play sounds. I’m using Visual Studio as an IDE instead of CodePen. I replaced the external links with local audio files I found online. When I use FCC’s audio links they play when clicked (but not when I use a keypress), but the local audio files I downloaded don’t work.
Your code so far
The main Drum Machine component:
import React, { Component } from "react";
import "./App.css";
import ReactFCCTest from "react-fcctest";
import Drumpad from "./components/drumpad";
const data = [
{ keyStroke: "Q", keyCode: 81, src: "./audio/drum1.wav", id: "Drum1" },
{ keyStroke: "W", keyCode: 87, src: "./audio/drum2.wav", id: "Drum2" },
{ keyStroke: "E", keyCode: 69, src: "./audio/drum3.wav", id: "Drum3" },
{ keyStroke: "A", keyCode: 65, src: "./audio/drum4.wav", id: "Drum4" },
{ keyStroke: "S", keyCode: 83, src: "./audio/drum5.wav", id: "Drum5" },
{
keyStroke: "D",
keyCode: 68,
src: "./audio/finger_cymbal.mp3",
id: "FingerCymbal"
},
{ keyStroke: "Z", keyCode: 90, src: "./audio/gong.mp3", id: "Gong" },
{ keyStroke: "X", keyCode: 88, src: "./audio/can.mp3", id: "Can" },
{ keyStroke: "C", keyCode: 67, src: "./audio/crescendo.mp3", id: "Crescendo" }
];
class App extends Component {
render() {
return (
<div>
<ReactFCCTest />
<div id="drum-machine">
<div id="display" />
{data.map(x => (
<Drumpad
keyStroke={x.keyStroke}
src={x.src}
id={x.id}
keyCode={x.keyCode}
/>
))}
</div>
</div>
);
}
}
export default App;
The Drumpad component:
import React, { Component } from "react";
export default class Drumpad extends Component {
constructor(props) {
super(props);
this.state = {};
this.playMusic = this.playMusic.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
playMusic = () => {
const sound = document.getElementById(this.props.keyStroke);
sound.currentTime = 0;
sound.play();
};
componentDidMount() {
document.addEventListener("keydown", this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyPress);
}
handleKeyPress(e) {
if (e.keyCode === this.props.keyCode) {
this.playMusic();
}
}
render() {
return (
<div className="drum-pad" id={this.props.id} onClick={this.playMusic}>
<p>{this.props.keyStroke}</p>
<audio
className="clip"
src={this.props.src}
id={this.props.keyStroke}
key={this.props.id}
/>
</div>
);
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
.
Link to the challenge: