JavaScript和绑定键问题

问题描述 投票:0回答:1

我正在尝试为我正在研究的新项目制作一个(超级)简单的软件工具。我这样做的方式类似于Garageband的“音乐打字”,其中某些音符绑定到键盘上的某些键。我一直试图将超小型mp3(每个〜100kb)绑定到按钮和按键。我这样做的方式如下:

    var a = document.createElement('audio');
    var s = document.createElement('audio');
    var d = document.createElement('audio');
    var f = document.createElement('audio');

    a.setAttribute('src', 'Sounds/a.mp3');

    $('.a').click(function() {
       a.currentTime = 0;
       a.play();
    });

    $(document).jkey('a',function(){
       a.currentTime = 0;
       a.play();
       return false;
    });

对于键绑定,我正在使用jKey jquery插件。

(大多数情况下,情况正常,但存在一些问题:

  1. 在Chrome浏览器中,当按下键或按钮时,声音会跳过,然后看起来会很快又重新开始。 Firefox不起作用(firebug表示与.currentTime有关),但Safari可以完美运行。

  2. 当按下按键时,我希望它不会继续执行该功能。当前,按住键不停地重播该位,从而产生“ dun dun dun dun dun dun dun dun dun dun dun”的声音。

非常感谢您提供有关如何解决以下问题的建议。我尝试了在Javascript中绑定键的常规方法,但得到的结果相同,所以我知道它不是jKey。

[此外,如果有人对如何以完全不同/更好的方式进行此操作有任何建议,请随时告诉我!谢谢!

我还应该提到,.current时间是这样,因此一旦按下按钮,它就会开始重播音符。

jquery audio dom-events instruments keyboard-events
1个回答
0
投票

我不熟悉jKey,但我相信如果按住某个键,大多数浏览器的确会生成多个keydown事件,所以我想这可以解释您提到的“ dun dun dun dun”声音。一般而言,如果您想在按下某个键时只执行一次操作,那么我认为您将需要某种在击键时重置的标志。我建议像这样使事情保持整洁:

var keyNotes = {
       addNote : function(key, audioSrc) {
           var el = document.createElement('audio');
           el.setAttribute('src', audioSrc);
           // any other element init here, presumably you
           // append it to some container, then:

           this[key] = {
               audio   : el,
               canPlay : true
           };
       },
       play : function(key) {
           var note = this[key];
           // if note has been defined for this key, and can be played
           if (note && note.canPlay) {
               note.canPlay = false;
               note.audio.currentTime = 0;
               note.audio.play();
           }
       },
       stop : function(key) {
           var note = this[key];
           if (note && !note.canPlay) {
              note.canPlay = true;
              note.audio.pause(); // or should this be .stop()?
           }
       }
    };

keyNotes.addNote("a", "Sounds/a.mp3");
keyNotes.addNote("s", "Sounds/b.mp3");
keyNotes.addNote("d", "Sounds/c.mp3");
keyNotes.addNote("f", "Sounds/d.mp3");

$(document).keydown(function(e){
    keyNotes.play(noteFromKeyCode(e.which));
    return false;
}).keyup(function(e){
    keyNotes.stop(noteFromKeyCode(e.which));
});

function noteFromKeyCode(keyCode) {
    return String.fromCharCode(keyCode).toLowerCase();
}

((您需要检查是否存在语法错误,但我希望总体思路是显而易见的。)

© www.soinside.com 2019 - 2024. All rights reserved.