未捕获的TypeError:无法读取null的属性'createMediaElementSource'

时间:2018-12-12 09:57:35

标签: javascript html web-audio-api

你好,我有一个项目JavaScript,它对我来说是新的,我使用音频Web API,该代码允许我播放音乐并使用相同的按钮停止,一切似乎都很好,但是控制台显示此消息错误,请任何人可以帮助我来解决这个问题,如果您还有其他问题,请告诉我tnx。

就是问题

  

(未捕获的TypeError:无法读取属性'createMediaElementSource'   的null       在HTMLButtonElement。 (h1.html?_ijt = o00si3cs9lv3ovov0so3fv3a4h:33)(匿名)@   h1.html?_ijt = o00si3cs9lv3ovov0so3fv3a4h:33)。

这是我的代码:

 <html>
<body>
<section class="tape">

    <audio src="outfoxing.mp3" crossorigin="anonymous" ></audio>

    <!--            type="audio/mpeg" -->

    <button data-playing="false" class="tape-controls-play" role="switch" aria-checked="false">
        <span>Play/Pause</span>
    </button>
</section>
<script>
    const AudioContext = window.AudioContext;
    let audioCtx = null;
    //play video
    let playButton = document.querySelector('.tape-controls-play');
    let audioElement =null ;

        playButton.addEventListener('click', function() {

          let  track= new AudioContext();
            audioElement = document.querySelector('audio');
            audioCtx= audioCtx.createMediaElementSource(audioElement);

        // check if context is in suspended state (autoplay policy)
        if (audioCtx.state === 'suspended') {
            audioCtx.resume();
        }

        if (this.dataset.playing === 'false') {
            audioElement.play();
            this.dataset.playing = 'true';
            // if track is playing pause it
        } else if (this.dataset.playing === 'true') {
            audioElement.pause();
            this.dataset.playing = 'false';
        }

        let state = this.getAttribute('aria-checked') === "true" ;
        this.setAttribute( 'aria-checked', state ? "false" : "true" );

// connect our graph
            audioElement.addEventListener('ended', () => {
                playButton.dataset.playing = 'false';
                playButton.setAttribute( "aria-checked", "false" );
                track.connect(audioCtx.destination);
            }, false);

    }, false);

</script>

</body>
</html>

编辑:

按照下面的答案中的@chŝdk的建议,在编辑了代码之后,您可以:

audioCtx= track.createMediaElementSource(audioElement);

我不断收到以下警告:

  

AudioContext不允许启动。用户在页面上进行手势操作后,必须恢复(或创建)

这个问题有解决方案吗?

1 个答案:

答案 0 :(得分:1)

您收到此错误,是因为您试图在此行的createMediaElementSource变量null上调用audioCtx方法:

audioCtx= audioCtx.createMediaElementSource(audioElement);

AudioContext.createMediaElementSource() MDN reference 中,我们可以看到应该在AudioContext实例上调用此方法,因此在您的代码中,您将需要在{{1 }}变量。

所以只需将上面的行更改为:

track
相关问题