Skip to content

Instantly share code, notes, and snippets.

@deveedutta
Created October 6, 2016 22:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deveedutta/13fccfeba982be606c916d1c7e2f3e09 to your computer and use it in GitHub Desktop.
Save deveedutta/13fccfeba982be606c916d1c7e2f3e09 to your computer and use it in GitHub Desktop.
Chord React component that plays a combination of 3 oscillators to generate a Chord
// A Chord react (or call it preact) component that plays a combination of 3 oscillators
// And generates various chords
// <Chord chordname="C Major" frequencies="196.00, 261.63, 329.63" type="sine" />
import { h, Component } from 'preact';
import style from './style';
const audioContext = new (window.AudioContext || window.webkitAudioContext);
export default class Chord extends Component {
play() {
if( this.oscillators ) return;
this.oscillators = [];
var THIS = this;
this.props.frequencies.split(",").forEach(function(item, index){
var oscillator = audioContext.createOscillator();
oscillator.type = THIS.props.type || 'sine';
oscillator.frequency.value = (item * 1) || 329.63; //E(1) is default
oscillator.connect(audioContext.destination);
oscillator.start();
THIS.oscillators.push( oscillator );
});
}
stop() {
if(!this.oscillators) return;
this.oscillators.forEach(function(oscillator, index){
oscillator.stop();
oscillator = null;
});
this.oscillators = null;
}
render() {
return (
<div>
<table class={style.w_70}>
<tr>
<td>
<strong>{this.props.chordname}</strong>
</td>
<td>{this.props.frequencies}</td>
<td>
<button onClick={this.play.bind(this)}>start</button>
&nbsp; &nbsp;
<button onClick={this.stop.bind(this)}>stop</button>
</td>
</tr>
</table>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment