使用网络音频API播放简单的声音 [英] Playing a simple sound with web audio api

查看:128
本文介绍了使用网络音频API播放简单的声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试遵循一些教程中的步骤,使用Web Audio API通过按钮播放简单的,编码的本地wav或mp3文件.我的代码如下(testAudioAPI.js):

I've been trying to follow the steps in some tutorials for playback of a simple, encoded local wav or mp3 file with the web Audio API using a button. My code is the following (testAudioAPI.js):

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var myBuffer;

clickme = document.getElementById('clickme');
clickme.addEventListener('click',clickHandler);

var request = new XMLHttpRequest();

request.open('GET', 'WoodeBlock_SMan_B.wav', true);

request.responseType = 'arraybuffer';

// Decode asynchronously
request.onload = function() {
  context.decodeAudioData(request.response, function(theBuffer) {
    myBuffer = theBuffer;
  }, onError);
}
request.send();

function playSound(buffer) {
  var source = context.createBufferSource(), g = context.createGain();
  source.buffer = buffer;
  source.start(0);
  g.gain.value = 0.5;
  source.connect(g);
  g.connect(context.destination);
}

function clickHandler(e) {
    playSound(myBuffer);
}

HTML文件如下所示:

And the HTML file would look like this:

    <!doctype html>
<html>
    <body>
        <button id="clickme">Play</button>
        <script src='testAudioAPI.js'></script>
    </body>
</html>

但是,没有任何声音.我已经尝试了多个代码段,但仍然无法弄清楚.当我尝试通过创建振荡器节点来通过合成声音来生成声音时,我确实会获得声音,但是没有本地文件的缓冲区.这是什么问题?谢谢你们.

However, no sound is achieved whatsoever. I've tried several snippets but I still can't figure it out. When I try to generate a sound by synthesizing it by creating an oscillator node, I do get sound, but not with buffers from local files. What would be the problem here? Thank you all.

推荐答案

本地文件,是吗?您是从文件系统(例如"file://")中获取它们,还是正在运行本地Web服务器?

Local files, huh? Are you just grabbing them from the filesystem (e.g. "file://"), or do you have a local web server running?

据我回忆,在大多数(所有?)浏览器中,直接从文件系统提供服务都违反了CORS,这将阻止您的AJAX请求成功.

From what I recall, serving directly from the filesystem violates CORS in most (all?) browsers – which will prevent your AJAX request from succeeding.

也许可以尝试使用python -m SimpleHTTPServer或类似名称投放页面,然后通过 http://localhost:8000 访问该页面

Maybe try serving the page with python -m SimpleHTTPServer or similar, and then access it at http://localhost:8000.

据我所知,您所有的代码看起来都很好.

From what I can tell, all of your code looks fine.

这篇关于使用网络音频API播放简单的声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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