Play a specific frequency with javascript

I need a function that works as follows:

playSound(345, 1000) 

which will reproduce a tone at 345 Hz for 1000 milliseconds. What is the easiest way to achieve this in JavaScript? I do not mind if he uses a sample (possibly for a sin wave or piano) or uses computer equipment to generate sound.

+9
source share
3 answers

As already mentioned in the comments, the way to do this 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(); 
+7
source

There is a library called simpleTones.js that greatly simplifies the web audio API to do exactly what you are trying to do.

When a library is included in your project, reproducing the time frequency is as easy as calling

playTone(345, sine, 1)

345 is the frequency in Hz, the sine is the wave pattern (there are other options for the wave pattern), and “1” is one second or 1000 milliseconds.

You can download the library and read the documentation here: https://github.com/escottalexander/simpleTones.js

Good luck in your project.

+1
source

Nonrelativistic, without external field: {\ displaystyle \ mathbf {j} = {\ frac {-i \ hbar} {2m}} \ left (\ Psi ^ {} \ nabla \ Psi - \ Psi \ nabla \ Psi ^ {} \ right)} \ mathbf {j} = \ frac {-i \ hbar} {2m} \ left (\ Psi ^ * \ nabla \ Psi - \ Psi \ nabla \ Psi ^ \ right) {\ displaystyle = {\ frac {\ hbar} {m}} \ mathrm {Im} (\ Psi ^ {} \ nabla \ Psi) = \ mathrm {Re} (\ Psi ^ {} {\ frac {\ hbar} {im}} \ nabla \ Psi)} = \ frac \ hbar m \ mathrm {Im} (\ Psi ^ \ nabla \ Psi) = \ mathrm {Re} (\ Psi ^ * \ frac {\ hbar} {im} \ nabla \ Psi)

star * is complex conjugate

0
source

All Articles