gpt4 book ai didi

api - 使用Mozilla音频API创建提示音

转载 作者:行者123 更新时间:2023-12-02 22:42:51 29 4
gpt4 key购买 nike

我正在研究使用mozilla音频API音调生成器:

  function AudioDataDestination(sampleRate, readFn) {
// Initialize the audio output.
var audio = new Audio();
audio.mozSetup(1, sampleRate);

var currentWritePosition = 0;
var prebufferSize = sampleRate / 2; // buffer 500ms
var tail = null, tailPosition;

// The function called with regular interval to populate
// the audio output buffer.
setInterval(function() {
var written;
// Check if some data was not written in previous attempts.
if(tail) {
written = audio.mozWriteAudio(tail.subarray(tailPosition));
currentWritePosition += written;
tailPosition += written;
if(tailPosition < tail.length) {
// Not all the data was written, saving the tail...
return; // ... and exit the function.
}
tail = null;
}

// Check if we need add some data to the audio output.
var currentPosition = audio.mozCurrentSampleOffset();
var available = currentPosition + prebufferSize - currentWritePosition;
if(available > 0) {
// Request some sound data from the callback function.
var soundData = new Float32Array(available);
readFn(soundData);

// Writting the data.
written = audio.mozWriteAudio(soundData);
if(written < soundData.length) {
// Not all the data was written, saving the tail.
tail = soundData;
tailPosition = written;
}
currentWritePosition += written;
}
}, 100);
}

// Control and generate the sound.

var frequency = 0, currentSoundSample;
var sampleRate = 44100;

function requestSoundData(soundData) {
if (!frequency) {
return; // no sound selected
}

var k = 2* Math.PI * frequency / sampleRate;
for (var i=0, size=soundData.length; i<size; i++) {
soundData[i] = Math.sin(k * currentSoundSample++);
}
}

var audioDestination = new AudioDataDestination(sampleRate, requestSoundData);

function start() {
currentSoundSample = 0;
frequency = parseFloat(document.getElementById("freq").value);
}

function stop() {
frequency = 0;
}

我希望此声音先打开500毫秒,然后关闭500毫秒,然后重复直到停止按钮被按下为止。我以为可以通过将样本数量22,050到44,100设置为零来做到这一点。但是,此方法似乎不起作用。我认为这是因为重新填充缓冲区的功能每100毫秒发生一次,但是现在这超出了我的知识范围。任何帮助将不胜感激。

最佳答案

实际上,它似乎对我来说很好用。我这样更改了requestSoundData函数中的循环:

for (var i=0, size=soundData.length; i<size; i++) {
if (currentSoundSample % 44100 < 22050)
soundData[i] = Math.sin(k * currentSoundSample);
else
soundData[i] = 0;
currentSoundSample++;
}

样本22,050到44,100被设置为零,这似乎完全产生了您想要的效果。在这里您可以尝试代码: http://jsfiddle.net/95jCt/

关于api - 使用Mozilla音频API创建提示音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374263/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com