繁体   English   中英

使用 javascript/html5 即时生成声音

[英]Generating sound on the fly with javascript/html5

是否可以使用 javascript/html5 生成恒定的声音 stream? 例如,要生成一个永久正弦波,我将有一个回调 function,只要 output 缓冲区即将变空,就会调用该回调:

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

(想法是用它来做一个交互式合成器。我事先不知道一个键会被按下多长时间,所以我不能使用固定长度的缓冲区)

您现在可以在大多数浏览器( IE 和 Opera Mini 除外)中使用Web 音频 API

试试这个代码:

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

我在阅读Web 音频 API 工作草案时进行了铬实验,获得了大部分内容,我从@brainjam 的链接中找到了该文件。

我希望这会有所帮助。 最后,在 chrome 检查器 (ctrl-shift-i) 中检查各种对象非常有帮助。

使用HTML5音频元件

正如 Steven Wittens在一篇关于创建 JavaScript 合成器的博客文章中指出的那样,使用 JavaScript 和audio元素目前无法实现跨浏览器生成持续音频:

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

使用 Web 音频 API

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

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

BBC 关于 Web 音频 API 的页面也值得一看。 不幸的是,对 Web 音频 API 的支持尚未扩展到其他浏览器。

可能的解决方法

目前要创建跨浏览器合成器,您可能必须通过以下方式使用预先录制的音频:

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

Web 音频 API 即将登陆 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

当然:您可以在此演示中使用音调合成器:

在此处输入图像描述

 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 发出哔哔声?

您可以在此处克隆和调整代码: Tone synthesizer demo on JS Bin

兼容的浏览器:

  • Chrome 移动设备和桌面设备
  • Firefox 移动和桌面 Opera 移动、迷你和桌面
  • Android浏览器
  • 微软边缘浏览器
  • iPhone 上的 Safari 或 iPad

不兼容

  • Internet Explorer 版本 11(但可以在 Edge 浏览器上运行)

您可以即时生成 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>

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

您可以从 JavaScript 中调用 ActionScript 函数。

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

这就是我一直在寻找的东西,最后我设法按照自己的意愿自己做到了。 也许你也会喜欢它。 简单的 slider 带频率和推开/关:

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

您可以使用以下代码生成声音并尝试使用不同的频率来生成更多声音:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM