Reputation: 65
I am trying to play a short mp3 of a bird chirping when the submit button is clicked. I have the mp3 file in my folder with the rest of my components. It is called Chirps.mp3. How would I go about doing this? I want the sound every-time it is clicked. I don't want the user to have the ability to pause the sound if clicked again before it is finished playing.
This answer doesn't really apply to my situation and being new to react the extra features confused me: How do I play a sound in React
import React, { Component } from 'react'
export class AddChirp extends Component {
state = {
userName: '',
chirp: ''
}
onSubmit = (e) => {
e.preventDefault();
this.props.addChirp(this.state.userName, this.state.chirp);
this.setState({ chirp: '', userName: '' });
}
onChange = (e) => this.setState({ [e.target.name]: e.target.value });
render() {
return (
<form onSubmit={this.onSubmit} >
<input
className="col-2 p-3 mb-3 mt-3 bg-danger text-dark"
type="text"
name="userName"
placeholder="Username"
value={this.state.userName}
onChange={this.onChange}
></input>
<input
className="col-9 p-3 mb-3 mt-3 bg-danger text-dark"
type="text"
name="chirp"
placeholder="Chirp"
value={this.state.chirp}
onChange={this.onChange}
></input>
<button className=" col-1 btn btn-danger p-3 mb-4 mt-3">Submit</button>
</form>
)
}
}
export default AddChirp
Upvotes: 1
Views: 3285
Reputation: 65
Okay so after pulling my hair out and getting no real help here this is the working solution I came up with. Hope this helps anybody who stumbles across this who has a similar question.
import ChirpMP3 from './chirps.mp3'
export class AddChirp extends Component {
state = {
userName: '',
chirp: ''
}
onSubmit = (e) => {
e.preventDefault();
this.props.addChirp(this.state.userName, this.state.chirp);
this.setState({ chirp: '', userName: '' });
}
onChange = (e) => this.setState({ [e.target.name]: e.target.value });
onClick =()=>{
var ChirpChirp = new Audio (ChirpMP3);
ChirpChirp.play();
}
render() {
return (
<form onSubmit={this.onSubmit} >
<input
className="col-2 p-3 mb-3 mt-3 bg-danger text-dark"
type="text"
name="userName"
placeholder="Username"
value={this.state.userName}
onChange={this.onChange}
></input>
<input
className="col-9 p-3 mb-3 mt-3 bg-danger text-dark"
type="text"
name="chirp"
placeholder="Chirp"
value={this.state.chirp}
onChange={this.onChange}
></input>
<button onClick={this.onClick} className=" col-1 btn btn-danger p-3 mb-4 mt-3">Submit</button>
</form>
)
}
}
export default AddChirp
Upvotes: 4