加载音频缓冲区并使用音频标签播放 [英] Loading an Audio buffer and play it using the audio tag

查看:119
本文介绍了加载音频缓冲区并使用音频标签播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL加载音频缓冲区,然后再播放它.我从 HTML5 Rocks教程中获得了大部分代码.

I am trying to load an audio buffer from an URL, and then to play it. I got most of the code form this HTML5 Rocks Tutorial.

var request = new XMLHttpRequest();
request.open('GET', $(this).attr('data-url'), true);
request.responseType = 'arraybuffer';

request.onload = function() {
    console.log(request);
    context.decodeAudioData(request.response, function(buffer) {
        console.log(buffer);
        $('#play').click(function() {
              var source = context.createBufferSource();
              source.connect(context.destination);
              source.noteOn(0);
        }).removeAttr('disabled');
    }, function(err) { console.log(err); });
};
request.send();

但是,然后按#play按钮,什么也没发生. source.noteOn(0)被调用,我使用调试器对其进行了检查.并且所有对象均已正确加载和创建,但是我听不到声音.

However, then I press the #play button, nothing happens. source.noteOn(0) is called, I checked it using the debugger. And all of the objects are properly loaded and created, but I hear no sound.

而且,看起来,当我使用这种方法时,我将需要用所有控件重建一个完整的播放器.为了节省工作并确保更好地工作,我想做的就是将buffer放入<audio/>,以便可以在其中播放.

Also, as it seems, I would need to rebuild a complete player with all controls when I am using this approach. What I'd like to do, to save work and to ensure this works better, is to put the buffer into an <audio/>, so it can be played there.

我知道这里有audio.src用于放置文件名,但是我需要使用音频缓冲区.我已经尝试过

I know there is audio.src for putting the file name in there, but I need to use the audio buffer. I've tried

audio.src = buffer;
audio.load()

但是那没用.

那里有任何信息吗?

推荐答案

如果您只想播放音频文件,为简单起见,您可能希望使用<audio>标记. (并且不限于Webkit浏览器).

If you just want to play audio-files, you probably want to use the <audio> tag for sake of simplicity. (and for not being limited to webkit browsers).

在您的示例中,您未设置缓冲区-源节点的缓冲区:
如果要保持整体结构,只需添加source.buffer = buffer行,例如:

In your example you do not set the buffer of your buffer-source node:
if you want to keep the overall structure, you can simply add the line source.buffer = buffer, like:

context.decodeAudioData(request.response, function(buffer) {
    $('#play').click(function() {
          var source = context.createBufferSource();
          source.buffer = buffer;
          source.connect(context.destination);
          source.noteOn(0);
    }).removeAttr('disabled');
}, function(err) { console.log(err); })

(通过将音频解码与事件处理分开,可以提高代码的可读性.

(your code's readability would improve by separating the audio decoding from the event-handling).

您在audio.src上的其他问题:
您应该将audio.src设置为音频文件的 URL .

your other question on audio.src:
you should set audio.src to the URL of the audio file.

这篇关于加载音频缓冲区并使用音频标签播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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