首页 > 解决方案 > 一键在tone.js中播放两个音符

问题描述

我正在开发一个网页游戏,点击一个按钮应该连续播放两个音符。我可以使用上传的音频文件和 audio.onended 回调来做到这一点。

function playMusic(){
    audio.src = music_array[music_counter++];
    audio.play();
    audio.onended = function(){
        playMusic();
    };
}

我可以使用上面的代码块来播放一首歌曲。但是,使用这种方法,我需要事先将所有音频文件上传到 html,我认为这不是一个好方法。因此,我出于同样的目的研究了tone.js,但我无法一个接一个地演奏音符。我试过像这样使用for循环:

music = ["C4;4n", "D4;4n", ...... , "G5;8n"];
for(var i=0; i<range; i++){
    parts = music[music_counter++].split(';');
    synth.triggerAttackRelease(parts[0], parts[1]);
}

for(var i=0; i<range; i++){
    playNote();
}

playNote(){
    parts = music[music_counter++].split(';');
    synth.triggerAttackRelease(parts[0], parts[1]);
}

没有运气。我也查看了他们的文档和其他 stackoverflow 帖子。我一直无法弄清楚解决方案。有没有人有任何想法如何实现这一目标?

标签: javascripttone.js

解决方案


我终于想出了办法。

var synth = new Tone.Synth().toMaster();

var music = [{"time": 0, "note": "A4", "duration": "16n"},
         ......
         {"time": 23.5, "note": "A4", "duration": "8n"},
         {"time": 24, "note": "G4", "duration": "4n"}];

function playMusic(){
    var part = new Tone.Part(function(time, note){
        //the notes given as the second element in the array
        //will be passed in as the second argument
        console.log(note);
        synth.triggerAttackRelease(note.note, note.duration, time);
    }, music).start(0);

    Tone.Transport.start();
}

推荐阅读