gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'createMediaElementSource' of null

转载 作者:搜寻专家 更新时间:2023-10-31 08:50:04 25 4
gpt4 key购买 nike

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

这就是问题所在

(Uncaught TypeError: Cannot read property 'createMediaElementSource' of null at HTMLButtonElement. (h1.html?_ijt=o00si3cs9lv3ovov0so3fv3a4h:33) (anonymous) @ 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);

我不断收到以下警告:

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page

这个问题有什么解决方案吗?

最佳答案

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

audioCtx= audioCtx.createMediaElementSource(audioElement);

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

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

audioCtx= track.createMediaElementSource(audioElement);

关于javascript - 未捕获的类型错误 : Cannot read property 'createMediaElementSource' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com