首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Web Audio API:如何加载另一个音频文件?

Web Audio API:如何加载另一个音频文件?
EN

Stack Overflow用户
提问于 2012-07-10 22:29:11
回答 1查看 2.7K关注 0票数 0

我想写一个HTML5网络音频应用编程接口的基本脚本,可以播放一些音频文件。但我不知道如何卸载一个播放的音频并加载另一个。在我的脚本中,两个音频文件同时播放,但不是我想要的。

下面是我的代码:

代码语言:javascript
运行
复制
var context, 
    soundSource, 
    soundBuffer;

// Step 1 - Initialise the Audio Context
context = new webkitAudioContext();

// Step 2: Load our Sound using XHR
function playSound(url) {
    // Note: this loads asynchronously
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "arraybuffer";

    // Our asynchronous callback
    request.onload = function() {
        var audioData = request.response;
        audioGraph(audioData);
    };

    request.send();
}

// This is the code we are interested in
function audioGraph(audioData) {
    // create a sound source
    soundSource = context.createBufferSource();

    // The Audio Context handles creating source buffers from raw binary
    soundBuffer = context.createBuffer(audioData, true/* make mono */);

    // Add the buffered data to our object
    soundSource.buffer = soundBuffer;

    // Plug the cable from one thing to the other
    soundSource.connect(context.destination);

    // Finally
    soundSource.noteOn(context.currentTime);
}

// Stop all of sounds
function stopSounds(){
    // How can do this?
}


// Events for audio buttons
document.querySelector('.pre').addEventListener('click', 
    function () {
        stopSounds();
        playSound('http://thelab.thingsinjars.com/web-audio-tutorial/hello.mp3');
    }
);
document.querySelector('.next').addEventListener('click',
    function() {
        stopSounds();
        playSound('http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3');
    }
);
EN

回答 1

Stack Overflow用户

发布于 2012-07-10 23:38:59

你应该预先加载声音到缓冲区一次,在启动时,并简单地重置AudioBufferSourceNode,每当你想要播放它。

要按顺序播放多个声音,您需要基于缓冲区各自的长度,使用noteOn(time)逐个安排它们。

要停止声音,请使用noteOff

听起来你遗漏了一些基本的网络音频概念。此HTML5Rocks tutorialFAQ中的示例详细描述了这一点(以及更多内容)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11415555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档