使用 javascript/html5动态生成声音

有没有可能用 javascript/html5生成一个恒定的声音流?例如,要生成一个永久的正弦波,我需要一个回调函数,当输出缓冲区即将变为空的时候,就会调用这个函数:

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

(我们的想法是用它来制作一个交互式合成器。我不知道提前按下一个键需要多长时间,所以我不能使用固定长度的缓冲区)

52961 次浏览

使用 HTML5音频元素

跨浏览器生成持续的音频使用 JavaScript 和 audio元素目前是不可能的,因为史蒂芬威腾 在一篇关于创建 JavaScript 合成器的博客文章中提到:

“ ... 没有办法将合成音频块排队进行无缝播放”。

使用 Web 音频 API

网络音频 API旨在促进 JavaScript 音频合成。这个 Mozilla Developer Network 有一个可以在 firefox4 + [ 演示1]中工作的 基于 Web 的声调发生器。将这两行代码添加到该代码中,您就拥有了一个可以在按键时生成持续音频的工作合成器[ 演示2-仅适用于 Firefox 4,首先单击“ Results”区域,然后按任意键] :

window.onkeydown = start;
window.onkeyup = stop;

BBC 的 网络音频 API 页面也值得一看,不幸的是,对网络音频 API 的支持还没有扩展到其他浏览器。

可能的解决办法

目前,要创建跨浏览器合成器,你可能需要依靠预先录制的音频:

  1. 使用长的预先录制的 ogg/mp3样本音调,将它们嵌入单独的 audio元素中,并在按键时启动和停止它们。
  2. 嵌入包含音频元素的 swf 文件并通过 JavaScript 控制播放。(这似乎是 谷歌一下 Les Paul Doodle采用的方法。)

网络音频应用程序编程接口即将登陆 Chrome,请参阅 http://googlechrome.github.io/web-audio-samples/samples/audio/index.html

按照“入门”中的说明,然后查看令人印象深刻的演示。

更新(2017) : 到目前为止,这是一个更加成熟的界面,这个 API 被记录在一个 https://developer.mozilla.org/en-us/docs/web/API/web_audio_api

你现在可以在大多数浏览器中使用 网络音频 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

如果你想降低音量,你可以这样做:

var context = new webkitAudioContext();
var osc = context.createOscillator();
var vol = context.createGain();


vol.gain.value = 0.1; // from 0 to 1, 1 full volume, 0 is muted
osc.connect(vol); // connect osc to vol
vol.connect(context.destination); // connect vol to context destination
osc.start(context.currentTime + 3); // start it three seconds from now

我在阅读 网络音频 API 工作草案的时候在铬中进行实验,从@brainjam 的链接中找到了大部分内容。

我希望这有所帮助。最后,它是非常有帮助的检查各种对象在铬检查(ctrl-shift-i)。

这不是您问题的真正答案,因为您已经要求使用 JavaScript 解决方案,但是您可以使用 ActionScript。它应该可以在所有主流浏览器上运行。

可以从 JavaScript 内部调用 ActionScript 函数。

通过这种方式,您可以包装 ActionScript 声音生成函数,并对其进行 JavaScript 实现。只需使用 AdobeFlex 构建一个小型 swf,然后将其作为 JavaScript 代码的后端。

当然! 你可以在这个演示中使用音调合成器:

enter image description here

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>

玩得开心!

我从 Houshalter 这里得到了解决方案: 如何让 Javascript 发出哔哔声?

你可以在这里克隆和修改代码: JS Bin 上的音调合成器演示

兼容浏览器:

  • Chrome 手机及台式电脑
  • 移动版 Firefox 和桌面版 Opera 移动版、迷你版和桌面版
  • Android 浏览器
  • MicrosoftEdge 浏览器
  • IPhone 或 iPad 上的 Safari 浏览器

不兼容

  • Internet Explorer 版本11(但可在 Edge 浏览器上使用)

这就是我一直在寻找的东西,最后我自己做到了,就像我想要的那样。也许你也会喜欢。 简单的滑块频率和推动/关闭:

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" />

您可以在动态过程中生成 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,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()

这是可视化

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>

你可以使用下面的代码产生声音,并尝试不同的频率产生更多的声音:

    // 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