javascript - 优化 iOS Web App 的音频

标签 javascript ios cordova audio web-applications

我目前正在使用 Javascript 和 Cordova 框架开发和测试一款 iOS 游戏。我试图在触摸某些节点时添加声音效果。由于节点可以以任何速率重复触摸。我正在使用...

var snd = new Audio("audio/note_"+currentChain.length+".mp3");
snd.play();

这可以满足我的需要,但是当我启用这些效果时,我发现游戏滞后。我正在处理大小已缩小至约 16kb 的 mp3 文件,但延迟仍然很大。

在我的情况下优化声音的最佳方法是什么?由于该应用程序不是 native 的,我的质量是否受到限制?

谢谢!

最佳答案

最好的选择是预加载它们并在需要时准备好。我刚刚写了一个快速的独立闭包,我认为它会向您展示您想知道如何做的大部分内容。

var playSound = (function () {
        var sounds = 15, // idk how many mp3 files you have
            loaded = new Array(sounds),
            current = -1,
            chain = [],
            audio,
            i;

        function incrementLoaded(index) {
            loaded[index] = true;
        }

        // preloads the sound data
        for(i = 0; i < sounds; i++) {
            audio = new Audio();
            audio.addEventListener('canplay', incrementLoaded.bind(audio, i));
            audio.src = 'audio/note_' + i + '.mp3';
            chain.push(audio);
        }

        // this will play audio only when ready and in sequential order automatically
        // or "which" index, if supplied
        return function (which) {
            if(typeof which === 'number') {
                current = which;
            } else {
                current = (current + 1) % sounds;
            }

            // only play if loaded
            if(loaded[current]) {
                chain[current].pause();
                chain[current].currentTime = 0;
                chain[current].play();
            }
        };
    }());
// would play sounds in order every second
setInterval(function () {
    playSound();
}, 1000);

关于javascript - 优化 iOS Web App 的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894835/

相关文章:

Javascript 按键时间

ios - 在字符串中获取多个范围的动态字符串

iphone - 如何使用 MonoDevelop 和 MonoTouch 在设备上进行调试?

ios - 在导航 Controller xcode 中添加 "Sub" View

html - 我可以获取状态栏高度并将其应用到 HTML 中吗?

javascript - 为什么返回响应的格式很奇怪?

javascript - AngularJs - 在 Controller 函数中获取 ng-src 属性的值

android - 放大 android cordova 应用程序

javascript - 调用函数时出现 Backbone 问题

javascript - 为服务器上不存在文件的 URL 动态创建内容的正确方法