使用javascript / html5即时生成声音

问题描述

| 是否可以使用javascript / html5生成恒定的声音流?例如,要生成一个永久的正弦波,我将有一个回调函数,只要输出缓冲区即将变空,就会调用函数
function getSampleAt(timestep)
{
    return Math.sin(timestep);
}
(想法是使用它来制作交互式合成器。我事先不知道按键会被按下多久,所以我不能使用固定长度的缓冲区)     

解决方法

        使用HTML5音频元素 正如史蒂文·威滕斯(Steven Wittens)在有关创建JavaScript合成器的博客文章中指出的那样,目前无法使用JavaScript和
audio
元素跨浏览器生成持续音频。   \“ ...无法排队合成音频块以进行无缝播放\”。 使用网络音频API Web Audio API旨在促进JavaScript音频合成。 Mozilla开发人员网络具有一个基于Web的音调生成器,可在Firefox 4+中运行[示例1]。将这两行添加到该代码中,并在按下按键时就可以生成持续的音频[演示2-仅在Firefox 4中有效,首先单击'Results \'区域,然后按任意键]:
window.onkeydown = start;  
window.onkeyup = stop;
Web Audio API上的BBC页面也值得回顾。不幸的是,对Web Audio API的支持还没有扩展到其他浏览器。 可能的解决方法 目前,要创建跨浏览器的合成器,您可能需要通过以下方法来回退预先录制的音频: 使用预先录制的较长的ogg / mp3采样音,将它们嵌入到单独的
audio
元素中,并在按键时启动和停止它们。 嵌入包含音频元素的swf文件,并通过JavaScript控制播放。 (这似乎是Google Les Paul Doodle使用的方法。)     ,        您现在可以在大多数浏览器中使用Web Audio API(IE和Opera Mini除外)。 试用以下代码:
// one context per document
var context = new (window.AudioContext || window.webkitAudioContext)();
var osc = context.createOscillator(); // instantiate an oscillator
osc.type = \'sine\'; // this is the default - also square,sawtooth,triangle
osc.frequency.value = 440; // Hz
osc.connect(context.destination); // connect it to the destination
osc.start(); // start the oscillator
osc.stop(context.currentTime + 2); // stop 2 seconds after the current time
,        Web Audio API即将推出Chrome。参见http://googlechrome.github.io/web-audio-samples/samples/audio/index.html 按照此处的“入门”中的说明进行操作,然后查看非常出色的演示。 Update(2017):到目前为止,这是一个更加成熟的界面。在https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Audio_API中记录了该API     ,        当然!您可以在此演示中使用音调合成器:
audioCtx = new(window.AudioContext || window.webkitAudioContext)();

show();

function show() {
  frequency = document.getElementById(\"fIn\").value;
  document.getElementById(\"fOut\").innerHTML = frequency + \' Hz\';

  switch (document.getElementById(\"tIn\").value * 1) {
    case 0: type = \'sine\'; break;
    case 1: type = \'square\'; break;
    case 2: type = \'sawtooth\'; break;
    case 3: type = \'triangle\'; break;
  }
  document.getElementById(\"tOut\").innerHTML = type;

  volume = document.getElementById(\"vIn\").value / 100;
  document.getElementById(\"vOut\").innerHTML = volume;

  duration = document.getElementById(\"dIn\").value;
  document.getElementById(\"dOut\").innerHTML = duration + \' ms\';
}

function beep() {
  var oscillator = audioCtx.createOscillator();
  var gainNode = audioCtx.createGain();

  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);

  gainNode.gain.value = volume;
  oscillator.frequency.value = frequency;
  oscillator.type = type;

  oscillator.start();

  setTimeout(
    function() {
      oscillator.stop();
    },duration
  );
};
frequency
<input type=\"range\" id=\"fIn\" min=\"40\" max=\"6000\" oninput=\"show()\" />
<span id=\"fOut\"></span><br>
type
<input type=\"range\" id=\"tIn\" min=\"0\" max=\"3\" oninput=\"show()\" />
<span id=\"tOut\"></span><br>
volume
<input type=\"range\" id=\"vIn\" min=\"0\" max=\"100\" oninput=\"show()\" />
<span id=\"vOut\"></span><br>
duration
<input type=\"range\" id=\"dIn\" min=\"1\" max=\"5000\" oninput=\"show()\" />
<span id=\"dOut\"></span>
<br>
<button onclick=\'beep();\'>Play</button>
,        您可以即时生成wav-e文件并进行播放(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,SPS,NCH*BPS*SPS,[NCH*BPS,[BPS*8,2])}data${put(size)}`
  
  for (let i = 0; i < DUR*SPS; i++) {
    let f= Math.min(Math.max(fun(i/SPS,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()
,        这不是您问题的真实答案,因为您已请求JavaScript解决方案,但可以使用ActionScript。它应该在所有主要的浏览器上运行。 ActionScript API音频生成 您可以从JavaScript中调用ActionScript函数。 ActionScript API调用JavaScript 这样,您可以包装ActionScript声音生成函数并对其进行JavaScript实现。只需使用Adobe Flex构建一个小的swf,然后将其用作JavaScript代码的后端。     ,        这是我一直以来一直在寻找的东西,最终我设法按自己的意愿去做。也许您也会喜欢。 简单的滑块,带有频率并按开/关:
buttonClickResult = function () {
	var button = document.getElementById(\'btn1\');

	button.onclick = function buttonClicked()  {

		if(button.className==\"off\")  {
			button.className=\"on\";
			oscOn ();
		}

		else if(button.className==\"on\")  {
			button.className=\"off\";
			oscillator.disconnect();
		}
	}
};

buttonClickResult();

var oscOn = function(){

	window.AudioContext = window.AudioContext || window.webkitAudioContext;
	var context = new AudioContext();
	var gainNode = context.createGain ? context.createGain() : context.createGainNode();

	//context = new window.AudioContext();
	oscillator = context.createOscillator(),oscillator.type =\'sine\';

	oscillator.frequency.value = document.getElementById(\"fIn\").value;
	//gainNode = createGainNode();
	oscillator.connect(gainNode);
	gainNode.connect(context.destination);
	gainNode.gain.value = 1;
	oscillator.start(0);
};
<p class=\"texts\">Frekvence [Hz]</p>
<input type=\"range\" id=\"fIn\" min=\"20\" max=\"20000\" step=\"100\" value=\"1234\" oninput=\"show()\" />
<span id=\"fOut\"></span><br>
<input class=\"off\" type=\"button\" id=\"btn1\" value=\"Start / Stop\" />