I have a simple React component that should play audio via the Web Audio API on keyDown, and stop the audio on keyUp. I have a JSFiddle that shows the same behavior I'm seeing on localhost. Here's the code inline:
var Keyboard = React.createClass({
componentDidMount: function () {
var context = new (window.AudioContext || window.webkitAudioContext)();
var oscillator = context.createOscillator();
var gain = context.createGain();
oscillator.type = 'sine';
oscillator.frequency.value = 3000;
gain.gain.value = 0.5;
oscillator.connect(gain);
gain.connect(context.destination);
this.setState({
context: context,
oscillator: oscillator,
gain: gain
});
},
render: function() {
return (
<div id="keyboard"
onKeyDown={this.playNote}
onKeyUp={this.stopNote}>
</div>
);
},
playNote: function (ev) {
console.log('play');
this.state.oscillator.start();
},
stopNote: function (ev) {
console.log('stop');
this.state.oscillator.stop();
}
});
React.render(<Keyboard />, document.getElementById('container'));
Even without the Web Audio stuff, I can't get the log statements to show up. I've read the React Event System docs and didn't see anything that would help, and I've written other React components using mouse and change events with no problem -- it seems to be particular to keyboard events. Any help would be greatly appreciated!
Edit: Corrected web audio API call. Should've been start(), not play().