在Javascript上即时播放声音(无需等待完成) [英] Playing Sound Instantly (without waiting to complete) on Javascript

查看:199
本文介绍了在Javascript上即时播放声音(无需等待完成)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用html和.play的键部分地播放了声音.但是,它等待曲目完成,并且不允许我每次单击立即播放.但是,我想每次按一下就触发声音.

I partially achieved playing sound with keys with html and .play. However it waits for the track to be completed and doesn't let me play instantly on every click. However I want to trigger the sound as soon as I press it each time.

<audio id=soundId1>
  <source src=sound/Saaa.wav>
</audio>
<audio id=soundId2>
  <source src=sound/Baaa.wav>
</audio>


$(document).ready(function() {

var sound = {
    65 : 'soundId1',
    23 : 'soundId2'
};

document.onkeydown = function(e) {
    var soundId = sound[e.keyCode];

    if (soundId) document.getElementById(soundId).play();
    else console.log("key not mapped : code is", e.keyCode);

}

是否有一种方法可以仅使用上述方法而不使用任何库?

Is there a way of achieving it with the above approach only without using any library?

我也研究了howler.js(我不知道它是否正确使用),但我真的不明白如何将多个音轨添加到字典中.我知道如何将文件放入声音字典,但是如何调用它并将其链接到上面的keyCode系统?还是应该为每个声音分别添加new Howl?

I also looked into howler.js (I don't know if it's proper use) but I couldn't really understand how I can add multiple tracks into the dictionary. I understand how I can put the files into sounds dictionary however how to call it and link it to keyCode system above? Or should I add a new Howl for each sound individually?

实现它的正确方法是什么?

What is the proper way of achieving it?

推荐答案

这可能有效,但我还没有尝试过:

This may work but I have not tried it:

function Sound(){
    this.src = ""
}

function playSound(source){
    var sound = new Sound();
    sound.src = source;
    sound.play()
}

将创建一个新的声音实例,而不是覆盖先前的声音实例.

A new sound instance is created instead of overriding the previous one.

这篇关于在Javascript上即时播放声音(无需等待完成)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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