Tonejs / Tone.js

A Web Audio framework for making interactive music in the browser.
https://tonejs.github.io
MIT License
13.37k stars 976 forks source link

Get bar and beat numbers in loop #1142

Open swampthang opened 1 year ago

swampthang commented 1 year ago

The feature you'd like When creating a Player for an audio file with a loopStart and loopEnd set, I'd like to be able to get the current measure number as well as the current beat number during each pass of the loop.

Any alternatives you've considered In this codepen I created a Tone.ToneEvent that runs every quarter note. Here's the function that sets it up:

function setCallbackEvent() {

  displayScaleChange(scaleArr[0].scale);

  measureEvent = new Tone.ToneEvent(((time) => {
    let barsBeats = Tone.Time(time).toBarsBeatsSixteenths();
    let beat = parseInt(barsBeats.split(':')[1]);

    // beginning of new measure?
    if( beat === 0 ) {
      currentMeasure = currentMeasure+1 <= endMeasure ? currentMeasure+1 : startMeasure;
      console.log(currentMeasure);
      document.querySelector('.measure.selected').classList.remove('selected');
      document.querySelector(`.measure.m${currentMeasure}`).classList.add('selected');
      let obj = _.find(scaleArr, { 'measure': currentMeasure, 'beat': beat+1 });
      if( obj ) displayScaleChange(obj.scale);
    } else {
      let obj = _.find(scaleArr, { 'measure': currentMeasure, 'beat': beat+1 });
      if( obj ) displayScaleChange(obj.scale);
    }
  }));
  // loop it every quarter note
  measureEvent.loop = true;
  measureEvent.loopEnd = "4n";
}

As you can see I'm trying to get the current beat by running this...

let barsBeats = Tone.Time(time).toBarsBeatsSixteenths();
let beat = parseInt(barsBeats.split(':')[1]);

It works as long as I don't pause the player in the middle of a measure and then try to start over. When I do everything gets out of sync.

Additional context Maybe there are some hidden properties that I'm unaware of that would give me this data but I've not been able to turn up anything.

swampthang commented 1 year ago

I've handled the issue by adding a beat variable as well in this codepen but it would really be nice if measures and beats could be passed to a callback. Thanks.