Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play an mp3 once onClick in react?

Tags:

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)

like image 989
Christopher Ducote Avatar asked Jan 09 '19 16:01

Christopher Ducote


People also ask

How do I add sound to onClick in HTML?

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).


4 Answers

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;
like image 169
Hunter Avatar answered Sep 28 '22 12:09

Hunter


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;
like image 34
Codemaker Avatar answered Sep 28 '22 11:09

Codemaker


You need to pass a function thats trigger play:

<Container>
    <img src={dwight} onClick={ () => audio.play() }/>
 </Container>
like image 36
Artem Mirchenko Avatar answered Sep 28 '22 10:09

Artem Mirchenko


  1. Add to your render method<audio id="audio"><source src="slow-spring-board.mp3" type="audio/mp3"></source></audio>
  2. And inside the script document.getElementById('audio').play()
like image 22
Nagibaba Avatar answered Sep 28 '22 11:09

Nagibaba