I need a sample code that could:
generate sine wave (an array of samples) and then
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)
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.
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.
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.
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.
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)
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