【问题标题】:JavaScript Web Audio: cannot properly decode audio data?JavaScript Web Audio:无法正确解码音频数据?
【发布时间】:2014-10-19 15:31:22
【问题描述】:

我正在尝试使用 JavaScript 中的 Web Audio API 将声音加载到缓冲区中并播放。不幸的是,它不起作用,我收到以下错误:

Uncaught TypeError: Failed to set the 'buffer' property on 'AudioBufferSourceNode':
The provided value is not of type 'AudioBuffer'.

我可以查明是哪一行出现了错误,但我不知道为什么。如果有帮助,这里是相关代码:

var audioContext;
var playSoundBuffer;

function init() {
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new AudioContext();

    loadNote();
}

function loadNote() {
    var request = new XMLHttpRequest();
    request.open("GET", "./sounds/topE.wav", true);
    request.responseType = "arraybuffer";
    request.onload = function() {
        audioContext.decodeAudioData(request.response, function(buffer) {
            playSoundBuffer = buffer;
        }, function(error) {
            console.error("decodeAudioData error", error);
        });
    };
    request.send();

    playSound();
}

function playSound() {
    var source = audioContext.createBufferSource();
    source.buffer = playSoundBuffer;       // This is the line that generates the error
    source.connect(audioContext.destination);
    source.start(0);
}

我相信 decodeAudioData 方法会返回一个 AudioBuffer 到它的第一个回调函数(它的第二个参数)。我试图将这个 AudioBuffer 保存到“playSoundBuffer”然后播放它,但我得到了那个错误,我不知道为什么。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html web-audio-api


    【解决方案1】:

    您收到该错误的原因是您忽略了代码的异步特性,并将其视为同步的。如果您总是将所有相关部分的内容作为调试的第一步记录下来,您会意识到,在您尝试处理缓冲区时,它是 undefined 而根本不是 AudioBuffer。提示:始终使用 console.log everything,直到您确切知道它在任何时候的行为。

    function loadNote() {
        var request = new XMLHttpRequest();
        request.open("GET", "./sounds/topE.wav", true);
        request.responseType = "arraybuffer";
        request.onload = function() {
            audioContext.decodeAudioData(request.response, function(buffer) {
                playSoundBuffer = buffer;
                playSound(); // don't start processing it before the response is there!
            }, function(error) {
                console.error("decodeAudioData error", error);
            });
        };
        request.send();//start doing something async
    
    
    }
    

    【讨论】:

    • 非常感谢您的回复!您建议的编辑使声音正常播放。不幸的是,我并不真正了解异步函数是如何工作的。 playSound() 方法是否与 decodeAudioData 方法同时执行?那是具体导致错误的原因吗?再次感谢您的帮助!
    • 这是一篇文章 developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/… 在您的情况下,您实际上在 decodeAudioData 方法之前执行了 playSound() 方法,基本上是在您发送请求(异步)之后和请求之前到了,在你开始解码之前(这也是异步的)
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多