Search code examples
javascripttone.js

Calling Tone.JS function doesn't work second time


When I press the button the first time, it plays back the list of notes as expected, but not the second time. My console logging suggests that the second time around the function is called in the same way, but perhaps I am missing something? Why will this not play the sequence of notes the second time?

I tried e.g Tone.Transport.start(0) among other potential solutions but this didn't solve the problem.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src= "www/js/Tone.js"></script>
    <script src= "main.js"></script>
</head>
<body>

    <button onclick="playSeq([60, 61, 62], false, this.id, 'tone');">Play</button>

</body>
</html>

Javascript

function playSeq (note_list, hidePlay, id, sound) {


  midi_list = note_list.map(x => Tone.Frequency(x, "midi").toNote());
  last_note = midi_list.length;
  count = 0;
  var pattern = new Tone.Sequence(function(time, note){

  triggerNote(sound, note, 0.25);
  count = count + 1;

  if (count === last_note) {
  console.log("finished!");
  }

  }, midi_list);

  pattern.start(0).loop = false;

  console.log(Tone.Transport);
  // begin at the beginning
  Tone.Transport.start();


}

Solution

  • I had to call .stop() on the Transport and the Tone sequence objects after the finished playing back to solve the problem:

    if (count === last_note) {
          pattern.stop();
          Tone.Transport.stop();
        }