Generating sound on the fly with javascript/html5

Viewed 52330

Is it possible to generate a constant sound stream with javascript/html5? For example, to generate a perpetual sine wave, I would have a callback function, that would be called whenever the output buffer is about to become empty:

function getSampleAt(timestep)
{
    return Math.sin(timestep);
}

(The idea is to use this to make an interactive synth. I don't know in advance how long a key will be pressed, so I can't use a fixed length buffer)

8 Answers

You can generate wav-e file in the fly and play it (src)

// Legend
// DUR - duration in seconds   SPS - sample per second (default 44100)
// NCH - number of channels    BPS - bytes per sample

// t - is number from range [0, DUR), return number in range [0, 1]
function getSampleAt(t,DUR,SPS)
{
    return Math.sin(6000*t); 
}

function genWAVUrl(fun, DUR=1, NCH=1, SPS=44100, BPS=1) {
  let size = DUR*NCH*SPS*BPS; 
  let put = (n,l=4) => [(n<<24),(n<<16),(n<<8),n].filter((x,i)=>i<l).map(x=> String.fromCharCode(x>>>24)).join('');
  let p = (...a) => a.map( b=> put(...[b].flat()) ).join(''); 
  let data = `RIFF${put(44+size)}WAVEfmt ${p(16,[1,2],[NCH,2],SPS,NCH*BPS*SPS,[NCH*BPS,2],[BPS*8,2])}data${put(size)}`
  
  for (let i = 0; i < DUR*SPS; i++) {
    let f= Math.min(Math.max(fun(i/SPS,DUR,SPS),0),1);
    data += put(Math.floor( f * (2**(BPS*8)-1)), BPS);
  }
  
  return "data:Audio/WAV;base64," + btoa(data);
}


var WAV = new Audio( genWAVUrl(getSampleAt,5) ); // 5s
WAV.setAttribute("controls", "controls");
document.body.appendChild(WAV);
//WAV.play()

Here is visualistation

function getSampleAt(t,DUR,SPS)
{
    return 0.5+Math.sin(15*t)/(1+t*t); 
}


// ----------------------------------------------

function genWAVUrl(fun, DUR=1, NCH=1, SPS=44100, BPS=1) {
  let size = DUR*NCH*SPS*BPS; 
  let put = (n,l=4) => [(n<<24),(n<<16),(n<<8),n].filter((x,i)=>i<l).map(x=> String.fromCharCode(x>>>24)).join('');
  let p = (...a) => a.map( b=> put(...[b].flat()) ).join(''); 
  let data = `RIFF${put(44+size)}WAVEfmt ${p(16,[1,2],[NCH,2],SPS,NCH*BPS*SPS,[NCH*BPS,2],[BPS*8,2])}data${put(size)}`
  
  for (let i = 0; i < DUR*SPS; i++) {
    let f= Math.min(Math.max(fun(i/SPS,DUR,SPS),0),1);
    data += put(Math.floor( f * (2**(BPS*8)-1)), BPS);
  }
  
  return "data:Audio/WAV;base64," + btoa(data);
}

function draw(fun, DUR=1, NCH=1, SPS=44100, BPS=1) {
  time.innerHTML=DUR+'s';
  time.setAttribute('x',DUR-0.3);
  svgCh.setAttribute('viewBox',`0 0 ${DUR} 1`);
  let p='', n=100; // n how many points to ommit
  for (let i = 0; i < DUR*SPS/n; i++) p+= ` ${DUR*(n*i/SPS)/DUR}, ${1-fun(n*i/SPS, DUR,SPS)}`;
  chart.setAttribute('points', p);
}

function frame() {
  let t=WAV.currentTime;
  point.setAttribute('cx',t)
  point.setAttribute('cy',1-getSampleAt(t))
  window.requestAnimationFrame(frame);
}

function changeStart(e) {
  var r = e.target.getBoundingClientRect();
  var x = e.clientX - r.left;
  WAV.currentTime = dur*x/r.width;
  WAV.play()
}

var dur=5; // seconds 
var WAV = new Audio(genWAVUrl(getSampleAt,dur));
draw(getSampleAt,dur);
frame();
.chart { border: 1px dashed #ccc; }
.axis { font-size: 0.2px}
audio { outline: none; }
Click at blue line (make volume to max):
<svg class="chart" id="svgCh" onclick="changeStart(event)">    
  <circle cx="0" cy="-1" r="0.05" style="fill: rgba(255,0,0,1)" id="point"></circle>
  <polyline id="chart" fill="none" stroke="#0074d9" stroke-width="0.01" points=""/>
  <text x="0.03" y="0.9" class="axis">0</text>
  <text x="0.03" y="0.2" class="axis">1</text>
  <text x="4.8" y="0.9" class="axis" id="time"></text>
</svg><br>

you can use the following code to generate sounds and try different frequencies to generate even more sounds:

    // generate sounds using frequencies
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();
oscillator.type = "triangle"; // "square" "sine" "sawtooth"
oscillator.frequency.value = frequency; // 440 is default (try different frequencies)
oscillator.connect(audioContext.destination); // connects to your audio output
oscillator.start(0); // immediately starts when triggered
oscillator.stop(0.5); // stops after 0.5 seconds
Related