Outsider
Outsider

Reputation: 1236

Playing two notes in tone.js on one button click

I am developing a web game where clicking on one button should play two notes consecutively. I am able to do it using uploaded audio files and audio.onended callback.

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

I can use the above code block to play an entire song. However, using this approach I would need to upload all the audio files to the html beforehand and I don't think that is a good approach. So, I was looking into tone.js for the same purpose, but I am not able to play notes one after the other. I have tried using for loop like this:

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]);
}

and

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

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

with no luck. I have looked into their documentation and other stackoverflow posts as well. I haven't been able to figure out the solution. Does anybody have any ideas how to achieve this?

Upvotes: 3

Views: 2336

Answers (1)

Outsider
Outsider

Reputation: 1236

I've finally figured out the way to do it.

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();
}

Upvotes: 2

Related Questions