K
K
Kot Kotov2021-01-26 14:13:43
JavaScript
Kot Kotov, 2021-01-26 14:13:43

How to fix decodeAudioData of undefined at FileReader.reader.onload?

I am getting this error

Uncaught TypeError: Cannot read property 'decodeAudioData' of undefined at FileReader.reader.onload (lvl.js:131)

In this part of the code
this.context = new AudioContext();
  this.mt;

  this.GetMt = function(){
    async function pasteAudio() {
      var blob = await (await fetch('scripts/testSound.mp3')).blob();

      dt = new DataTransfer();
      dt.items.add(new File([blob], 'scripts/testSound.mp3', {type: 'audio/mpeg'}));

      var files = dt.files;

      if (files.length == 0) return;
      var reader = new FileReader();

      reader.onload = function(fileEvent) {
       this.context.decodeAudioData(fileEvent.target.result, calcTempo);
      }
      reader.readAsArrayBuffer(files[0]);
    }
    pasteAudio();

    var calcTempo = function (buffer) {
      var audioData = [];
      // Take the average of the two channels
      if (buffer.numberOfChannels == 2) {
        var channel1Data = buffer.getChannelData(0);
        var channel2Data = buffer.getChannelData(1);
        var length = channel1Data.length;
        for (var i = 0; i < length; i++) {
          audioData[i] = (channel1Data[i] + channel2Data[i]) / 2;
        }
      } else {
        audioData = buffer.getChannelData(0);
      }

     this.mt = new MusicTempo(audioData);


      let wave1Spd = map(mt.tempo,0,350,1,25);
      let wave2Spd = map(mt.tempo,0,350,1,20);
      let wave3Spd = map(mt.tempo,0,350,1,15);
      root.style.setProperty('--spd', wave1Spd+"s");
      root.style.setProperty('--spd2', wave2Spd+"s");
      root.style.setProperty('--spd3', wave3Spd+"s");
      console.log(mt.tempo);

      this.isStarted = true;
      this.song.play();


      /*const audio = new Audio()
      audio.src = 'scripts/testSound.mp3'
      audio.play();
      textAlign(CENTER);
      textSize(32);
      fill(200);
      text('bpm~ '+mt.tempo, windowWidth/2, windowHeight/2);*/

    }
    return true;
  }

in this line
this.context.decodeAudioData(fileEvent.target.result, calcTempo);


Before that, this part worked, but I had to somehow edit the code and this can be seen from the prefixes,
this.
after which I started getting this error, as I understood the problem with FileReader, but I have no idea how to solve it.
Thanks in advance for reading and any help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kot Kotov, 2021-01-26
@kot123123

I just specified context not as
this.context
a
var context
and everything worked

D
DimaIs, 2021-01-26
@DimaIs

Perhaps, because this is a callback, the context is lost
Try:

reader.onload = function(fileEvent) {
       this.context.decodeAudioData(fileEvent.target.result, calcTempo);
      }.bind(this)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question