AgneyaKerure AgneyaKerure -3 years ago 85
Javascript Question

Tone.js not working with React

I want to implement a basic Tone Player to load a file from a folder and play it by pressing a button in ReactJS.

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Tone from 'tone';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Slider from 'material-ui/Slider';
import RaisedButton from 'material-ui/RaisedButton';


let sound = new Tone.Player("kick.wav").toMaster();
export default class App extends Component {

render() {

return(
<MuiThemeProvider>
<div>
<Slider min={0} max={100} step={10} className = "Slider1Test1" style={{height: 400}} axis="y"/>
<RaisedButton label="A" className = "RaisedB1Test1" style={{width: 10}}/>

<Slider min={0} max={100} step={10} className = "Slider2Test1" style={{height: 400}} axis="y"/>
<RaisedButton label="B" className = "RaisedB2Test1" style={{width: 10}}/>
</div>
</MuiThemeProvider>
);
}
}


But this gives an error:


Uncaught (in promise) DOMException: Unable to decode audio data modules.js?hash=625032f…:48100 Uncaught (in promise) Tone.Buffer:
could not decode audio data: kick.wav


I have tried "./kick.wav", "./kick.ogg", "./kick.mp3". I have tried giving complete paths. I have tried using only web audio by giving XMLHTTPRequest - it is the same error all the time.

I am new to react - please let me know if there is a correct way to do this. Do I need to use componentDidMount? ( I have tried using that as well. Please let me know the correct way to do it).
Thanks

Answer Source

It looks like you're using meteor and this is somehow blocking your request to the server to load your file. The easiest solution is to create a public folder in your root directory and place your samples in there. Then pass in ./kick.wav to your Tone.Player constructor. The constructor makes a GET request under the hood and will find your file automatically. Along with the changes I had to add this code to play the sample after the buffer had finished loading:

const x = new Tone.Player('./kick.wav').toMaster()
Tone.Buffer.on('load', () => {
    x.start();
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download