back · main · about · writing · notes · reading · d3 · now · contact


Playing a sound file with React and Webpack
4 Nov 2019 · 144 words

One

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

Two

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

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

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;  
}	

back · main · about · writing · notes · reading · d3 · now · contact