Generate sine wave and play it in the browser [closed]

ぃ、小莉子 提交于 2019-12-21 05:21:34

问题


I need a sample code that could:

  1. generate sine wave (an array of samples) and then

  2. 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)


回答1:


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)


来源:https://stackoverflow.com/questions/34708980/generate-sine-wave-and-play-it-in-the-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!