Reputation: 773
I'm trying to do my first TypeScript/React project and I'm running into issues.
Using this answer, I have managed to read and play sound from my mic and also display some sample analysis data in the console. Now i'm trying to translate it into TS. Going step by step, I've arrived at this:
export class Processor {
readonly BUFFER_SIZE = 16384;
audioContext: AudioContext;
gainNode: GainNode;
microphoneStream: MediaElementAudioSourceNode;
constructor() {
this.audioContext = new AudioContext();
console.log('audio is starting up ...');
if (navigator.getUserMedia) {
navigator.getUserMedia(
{ audio: true },
function (stream) {
startMicrophone(stream);
},
function (e) {
alert('Error capturing audio.');
});
} else {
alert('Seems like this browser might not be supported.');
}
}
private startMicrophone(stream: MediaStream) {
this.gainNode = this.audioContext.createGain();
this.gainNode.connect(this.audioContext.destination);
this.microphoneStream =
this.audioContext.createMediaStreamSource(stream);
}
}
Except the call to startMicrophone gives me
'Cannot find name 'startMicrophone'.'
I also tried to refer to it with this
, which results in a different error:
''this' implicitly has type 'any' because it does not have a type annotation.'
I don't know what I'm doing wrong and could really use a bit of guidance.
Upvotes: 1
Views: 7746
Reputation: 10071
Recommended: You have to use arrow function if you want to use this because if you write this inside function block it refers current function this not parent this.
export class Processor {
readonly BUFFER_SIZE = 16384;
audioContext: AudioContext;
gainNode: GainNode;
microphoneStream: MediaElementAudioSourceNode;
constructor() {
this.audioContext = new AudioContext();
console.log('audio is starting up ...');
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
},
(stream) => {
this.startMicrophone(stream);
},
(e) => {
alert('Error capturing audio.');
});
} else {
alert('Seems like this browser might not be supported.');
}
}
private startMicrophone(stream: MediaStream) {
this.gainNode = this.audioContext.createGain();
this.gainNode.connect(this.audioContext.destination);
this.microphoneStream =
this.audioContext.createMediaStreamSource(stream);
}
}
Another way is you can assign this to some other variable and use const self= this;
use self inside the function.
constructor() {
const self = this;
this.audioContext = new AudioContext();
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
},
function (stream) {
self.startMicrophone(stream);
},
function (e) {
alert('Error capturing audio.');
});
} else {
alert('Seems like this browser might not be supported.');
}
}
Upvotes: 6