display remaining time when playing samples
authorFrédéric Péters <fpeters@0d.be>
Wed, 22 Feb 2017 18:37:34 +0000 (19:37 +0100)
committerFrédéric Péters <fpeters@0d.be>
Sat, 1 Apr 2017 10:37:19 +0000 (12:37 +0200)
nanofun.js

index 3fd7203..9244d0b 100644 (file)
@@ -296,6 +296,7 @@ var nanofun = function() {
   self.initAudio = function() {
     self.sample_buffers = Array(16);
     self.samples = Array(16);
+    self.sample_start_times = Array(16);
     self.audioCtx = new window.AudioContext();
     self.touchGainNodes = Array(16);
     self.masterGainNode = self.audioCtx.createGain();
@@ -350,6 +351,7 @@ var nanofun = function() {
           var sample_idx = this.sample_idx;
           self.audioCtx.decodeAudioData(this.result, function(buffer) {
             sample_buffers[sample_idx] = buffer;
+            $nanotouch.find('span.duration').data('duration', buffer.duration);
             $nanotouch.find('span.duration').text(parseInt(buffer.duration) + 's');
             $nanotouch.removeClass('error').addClass('loaded');
           }, function(e) {
@@ -414,6 +416,20 @@ var nanofun = function() {
       var touchIdx = parseInt($(this).parent().data('touch'));
       self.touchGainNodes[touchIdx].gain.value = fraction * fraction;
     });
+
+    self.time_interval_id = setInterval(function() {
+      for (var i=0; i<16; i++) {
+        var sample = self.samples[i];
+        if (sample !== undefined) {
+          var start_time = self.sample_start_times[i];
+          var current_position = sample.context.currentTime - start_time;
+          var nanotouch = $('.nanotouch')[i];
+          var duration = $(nanotouch).find('span.duration');
+          var total_duration = parseFloat($(duration).data('duration'))
+          $(duration).text(parseInt(total_duration - current_position) + 's');
+        }
+     }
+    }, 250);
   }
 
   self.startSample = function(sample_idx) {
@@ -432,9 +448,12 @@ var nanofun = function() {
         sample.buffer = sample_buffer;
         sample.onended = function() {
           $(nanotouch).removeClass('playing');
+          var duration = $(nanotouch).find('span.duration');
+          $(duration).text(parseInt($(duration).data('duration')) + 's');
           self.samples[sample_idx] = undefined;
         }
         $(nanotouch).addClass('playing');
+        self.sample_start_times[sample_idx] = sample.context.currentTime;
         sample.start(0);
       }
     }