I want a function that works like this:
playSound(345, 1000)
Which would play a tone of 345 hz for 1000 milliseconds. What is the simplest way to achieve this in JavaScript? I don't mind if it uses a sample (maybe of a sin wave, or piano), or uses the computer's hardware to generate the sound.
As we discussed last time, we can measure the frequency of sound waves in hertz, based on how many times they repeat per second. When we have a sine wave, we can control the frequency by changing the speed by which its oscillator goes around the circle.
voice : inhale helium. Snares & drums: making it smaller, tightening, replacing with materials with higher sound velocity. Whistles: shortening, increasing the humidity of air. Doppler effect: reduce the distance between source and listener, while making the sound.
As already pointed out in the comments, the way to do it is through the OscillatorNode
.
// create web audio api context
var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
function playNote(frequency, duration) {
// create Oscillator node
var oscillator = audioCtx.createOscillator();
oscillator.type = 'square';
oscillator.frequency.value = frequency; // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();
setTimeout(
function() {
oscillator.stop();
playMelody();
}, duration);
}
function playMelody() {
if (notes.length > 0) {
note = notes.pop();
playNote(note[0], 1000 * 256 / (note[1] * tempo));
}
}
notes = [
[659, 4],
[659, 4],
[659, 4],
[523, 8],
[0, 16],
[783, 16],
[659, 4],
[523, 8],
[0, 16],
[783, 16],
[659, 4],
[0, 4],
[987, 4],
[987, 4],
[987, 4],
[1046, 8],
[0, 16],
[783, 16],
[622, 4],
[523, 8],
[0, 16],
[783, 16],
[659, 4]
];
notes.reverse();
tempo = 100;
playMelody();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With