Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate sine wave and play it in the browser [closed]

I need a sample code that could:

  1. generate sine wave (an array of samples) and then

  2. play it.

All done in browser using some HTML5 API in JavaScript.

(I am tagging this web-audio, although I am not 100% sure it is applicable)

like image 845
exebook Avatar asked Jan 10 '16 18:01

exebook


People also ask

How can we generate sine wave?

This circuit generates a sine wave by first generating a square wave, at the required frequency, with amplifier A1 that is configured as an astable oscillator with the frequency determined by R1 and C1. The two-pole low pass filter, using A2, filters the square wave output from A1.

What is sine wave mode?

A sine wave is a geometric waveform that oscillates (moves up, down, or side-to-side) periodically, and is defined by the function y = sin x. In other words, it is an s-shaped, smooth wave that oscillates above and below zero.

How do you get a sine wave in Simulink?

Set up the Sine Wave block to use the sin() math library function to calculate block output. On the Sine Wave block dialog box, set Time to Use external signal so that an input port appears on the block icon. Connect a clock signal to this input port using a Digital Clock block.

Can we hear sine wave?

People will hear the frequency of a sine wave as pitch, i.e., a high-frequency (often repeating) wave will sound like a high note, while a lower-frequency (not as often repeating) wave will sound like a lower note. Frequency and amplitude are independent of each other.


1 Answers

This is how to play 441 Hertz sine wave tone in the browser using the cross-browser AudioContext.

window.AudioContext = window.AudioContext || window.webkitAudioContext;

var context = new AudioContext();

function playSound(arr) {
  var buf = new Float32Array(arr.length)
  for (var i = 0; i < arr.length; i++) buf[i] = arr[i]
  var buffer = context.createBuffer(1, buf.length, context.sampleRate)
  buffer.copyToChannel(buf, 0)
  var source = context.createBufferSource();
  source.buffer = buffer;
  source.connect(context.destination);
  source.start(0);
}

function sineWaveAt(sampleNumber, tone) {
  var sampleFreq = context.sampleRate / tone
  return Math.sin(sampleNumber / (sampleFreq / (Math.PI * 2)))
}

var arr = [],
  volume = 0.2,
  seconds = 0.5,
  tone = 441

for (var i = 0; i < context.sampleRate * seconds; i++) {
  arr[i] = sineWaveAt(i, tone) * volume
}

playSound(arr)
like image 144
exebook Avatar answered Oct 19 '22 14:10

exebook