为什么振荡器的Web音频输出无法正常工作? [英] Why the web audio output from oscillator is not working as expected?

查看:78
本文介绍了为什么振荡器的Web音频输出无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

我想创建一个音频程序,可以播放从极低频到高频的音频.

I want to create an audio program that can play audio from very low frequency to high frequency.

但是,此代码会导致不同的输出(即使使用相同的设备):

However, this code results in different output (even with the same device):

  1. 声音突然发出-预期结果是逐渐发出.我确定我的听力是可以的,因为我已经请朋友们听了;
  2. 在相同的频率上声音听起来不同.

警告:运行此脚本之前,请将音量调到非常低的水平.

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
var oscillator = audioCtx.createOscillator();

var osc_arr = [];

function purgeSound(){
  osc_arr.forEach(function(v){
    try {
      v.stop();
      v.disconnect(audioCtx.destination);
    } catch (e) {}
  })
}

function playSoundAtFreq(fq){
  purgeSound();
  var osc = audioCtx.createOscillator();
  osc_arr.push(osc);
  osc.type = 'square';
  osc.frequency.setValueAtTime(fq, audioCtx.currentTime); // value in hertz
  $('#fff').val(fq);
  osc.connect(audioCtx.destination);
  osc.start();
}

$('#stop').click(function(){
  purgeSound();
  _break = true;
})

var _break = false;
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
var pointer = 0;
var go = appendAttemptAsync(10000);
async function appendAttemptAsync(range) {
  if(_break) return;
  var target = pointer+range;
  for (pointer; pointer<range; pointer++) {
    playSoundAtFreq(pointer);
    console.log(pointer)
    //if(pointer % 1 == 0) {
      await sleep(100)
    //}
  }
  return 5221;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='stop'>stop</button>
<input id="fff" type="text" />

警告:运行此脚本之前,请将音量调到非常低的水平.

感谢任何改进我代码的建议.

Thanks for any kind of suggestions to improve my code.

推荐答案

如果您希望振荡器像

If you want an Oscillator to sweep like in the YouTube video that you mentioned, you can do something like:

let osc = new OscillatorNode(audioCtx);
osc.connect(audioCtx.destination);
osc.frequency.setValueAtTime(20, audioCtx.currentTime);
osc.frequency.linearRampToValueAtTime(audioCtx.sampleRate / 2, audioCtx.currentTime + 300);
osc.start();

300更改为声音扫描的适当时间.我任意选择5分钟.

Change the 300 to some appropriate time over which the tone sweeps. I arbitrarily chose 5 minutes.

我不知道您的示例为什么不起作用,但是此代码段是使用WebAudio扫音的典型方法.

I do not know why your example doesn't work, but this snippet is the typical way to sweep a tone using WebAudio.

这篇关于为什么振荡器的Web音频输出无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆