首页 > 解决方案 > 网络音频 api 和嵌套函数

问题描述

我尝试创建一个音频缓冲区,其长度取决于音频文件的长度/持续时间。

我使用网络音频 API https://webaudio.github.io/web-audio-api/#offlineaudiocontext

 function getDuration(filename) {
        // Send XHR request for audio file to server.
            const request = new XMLHttpRequest();
            request.open('GET', gorilla.stimuliURL(filename));
            request.responseType = 'arraybuffer';
            request.onload = function() {
                    // Decode the audio.
                audioContext.decodeAudioData(request.response, function(buffer) {
                        // Load and arm the source buffer.
                    var tStimNew = buffer.duration;
                });
            }
            request.send();
        }  

我使用此功能获得音频文件的持续时间。我对其进行了测试,tStimNew 正是我所期望的。问题似乎是变量 tStimNew 只是函数的局部变量。但我想让变量 global 能够进一步使用它。

我必须在哪里/如何包含退货?这三个函数的嵌套对我来说太复杂了。

先感谢您!

标签: javascriptfunctionweb-audio-apiaudiocontext

解决方案


推荐阅读