audiocontext html5,webkitaudiocontext

I'm using the HTML5 webkitAudioContext to get the realtime levels of a user's microphone using this following code:

var liveSource;

function getLevel(){

var context = new webkitAudioContext();

navigator.webkitGetUserMedia({audio: true}, function(stream) {

liveSource = context.createMediaStreamSource(stream);

liveSource.connect(context.destination);

var levelChecker = context.createJavaScriptNode(4096, 1 ,1);

liveSource.connect(levelChecker);

levelChecker.connect(context.destination);

levelChecker.onaudioprocess = function(e) {

var buffer = e.inputBuffer.getChannelData(0);

var maxVal = 0;

// Iterate through buffer to check if any of the |values| exceeds 1.

for (var i = 0; i < buffer.length; i++) {

if (maxVal < buffer[i]) {

maxVal = buffer[i];

}

}

if(maxVal <= 0.01){

console.log(0.0);

} else if(maxVal > 1){

console.log(1);

} else if(maxVal > 0.2){

console.log(0.2);

} else if(maxVal > 0.1){

console.log(0.1);

} else if(maxVal > 0.05){

console.log(0.05);

} else if(maxVal > 0.025){

console.log(0.025);

} else if(maxVal > 0.01){

console.log(0.01);

}

};

});

}

getLevel();

If you copy and paste this in to your console and click your fingers near your microphone (assuming you've enabled microphone input) you'll see it works for a few seconds, then suddenly stops. It doesn't report any errors. Can anybody explain why this is happening? Thanks

See http://labs.dinahmoe.com/dynamicmusicengine/ for an example where the levels are working correctly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,它演示了如何在 HTML5 游戏中添加音效。该示例使用了 Web Audio API 来加载和播放音效。你可以将以下代码复制到你的 HTML 文件中,并将音效文件(.mp3 或 .wav)放在与 HTML 文件相同的目录下。 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>HTML5 游戏音效示例</title> </head> <body> <h1>HTML5 游戏音效示例</h1> <button onclick="playSound()">播放音效</button> <script> // 创建音频上下文 var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // 加载音效文件 function loadSound(url, callback) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function() { audioCtx.decodeAudioData(request.response, function(buffer) { callback(buffer); }); }; request.send(); } // 播放音效 function playSound() { loadSound('sound.mp3', function(buffer) { var source = audioCtx.createBufferSource(); source.buffer = buffer; source.connect(audioCtx.destination); source.start(0); }); } </script> </body> </html> ``` 在这个示例中,我们创建了一个按钮,当用户点击它时,会播放一个名为 "sound.mp3" 的音效文件。该文件将从服务器加载并使用 Web Audio API 加载到内存中。当音效准备好后,我们创建一个音频源,并将其连接到 AudioContext 的目标输出。最后,我们通过调用 `start()` 方法来播放音效。 注意:上面的代码仅仅是一个示例,如果你想在实际项目中使用它,你需要更完整和更健壮的代码来处理音效的加载和播放。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值