Playing a sound file with React and Webpack

One Link to heading

Get the sound file you want (e.g. sound.mp3) and put it somewhere in your src directory.

Two Link to heading

Add this to your webpack.config.js file. Make sure you have file-loader installed (run npm install --save-dev file-loader if you don’t.)

{
	test: /\.mp3$/,
	loader: 'file-loader',
	query: {
		name: 'static/media/[name].[hash:8].[ext]'
	}
}

Three Link to heading

Import the file at the top of your JavaScript file. Put the path relative to the JavaScript file you are loading the sound from.

import soundfile from '../sound.mp3'; 

Four Link to heading

Put this in whatever function you need to play the soundfile.

let sound = new Audio(soundfile);
sound.play(); 

Or if you define it in the component constructor, you can play and stop it with different functions.

class App extends React.Component {
  constructor(props){
    this.sound = new Audio(soundfile);
  }
}

play_sound(){
  this.sound.play(); 
}

stop_sound(){
  // There's no 'this.sound.stop()' function. Can you believe it?
  this.sound.pause(); 
  this.sound.currentTime = 0;  
}