i have a that i want to play a very small mp3 once that is in my public folder in my react app, there are so many different solutions to playing audio but none that are simple for react, i tried react-360 but there was a problem with one of the modules.
i've tried some react audio libraries, but they seem to be for audio players, i dont need a play button and a pause and a volume and all that. just want a simple sound effect
class App extends Component {
render() {
var audio = new Audio("../public/sound.mp3")
return (
<Container>
<img src={dwight} onClick={ audio.play() }/>
</Container>
);
}
}
(sound to play when click the image)
Audio play() Method The play() method starts playing the current audio. Tip: This method is often used together with the pause() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).
Hooks version (React 16.8+):
Minimal version.
Place your music file (mp3) in the public folder.
import React from 'react';
function App() {
let audio = new Audio("/christmas.mp3")
const start = () => {
audio.play()
}
return (
< div >
<button onClick={start}>Play</button>
</div >
);
}
export default App;
You can import the audio using import statement and create a Audio object and call the play() method using the instantiated object.
import React from "react";
import audio from './../assets/audios/success.mp3';
class AudioTest extends React.Component{
playAudio = () => {
new Audio(audio).play();
}
render() {
return (
<div>
<button onClick={this.playAudio}>PLAY AUDIO</button>
</div>
);
}
}
export default AudioTest;
You need to pass a function thats trigger play:
<Container>
<img src={dwight} onClick={ () => audio.play() }/>
</Container>
<audio id="audio"><source src="slow-spring-board.mp3" type="audio/mp3"></source></audio>
document.getElementById('audio').play()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With