找不到功能名称

时间:2018-03-09 12:31:56

标签: typescript

我正在尝试执行我的第一个TypeScript / React项目,而且我遇到了问题。

使用this answer,我设法从麦克风中读取和播放声音,并在控制台中显示一些样本分析数据。现在我试图将其翻译成TS。我一步一步走到这里:

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);
    }
}

除了调用startMicrophone给我

'Cannot find name 'startMicrophone'.'

我还尝试用this引用它,这导致了不同的错误:

''this' implicitly has type 'any' because it does not have a type annotation.'

我不知道我做错了什么,并且真的可以使用一些指导。

1 个答案:

答案 0 :(得分:4)

推荐:如果你想使用它,你必须使用箭头功能,因为如果你在功能块中写这个,它引用当前函数,这不是父函数。

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);
    }
}

另一种方法是你可以将它分配给其他变量并使用const self= this;在函数内部使用self。

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.');
    }
}