Skip to content

Instantly share code, notes, and snippets.

@deveedutta

deveedutta/chord.js

Created Oct 6, 2016
Embed
What would you like to do?
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