Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a specific frequency with Javascript?

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.

like image 392
Robin Andrews Avatar asked Aug 29 '16 07:08

Robin Andrews


People also ask

Can we change frequency of 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.

How can the frequency of sound be increased?

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.


1 Answers

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();
like image 103
Giacomo Tecya Pigani Avatar answered Sep 28 '22 04:09

Giacomo Tecya Pigani