如何修复Wavesurfer.js中‘Cannot read properties of undefined (reading 'stop') at tostop’错误?
问题:Wavesurfer.js点击音频项停止当前播放时出现"Cannot read properties of undefined (reading 'stop')"错误
我在网站中使用Wavesurfer.js播放音频,需求是点击其他音频项时停止当前播放的音频,但控制台报错"Cannot read properties of undefined (reading 'stop') at tostop",相关代码如下:
<script> function toknown(from){ window.play = from; } function tostop( ){ window.play.stop(); } </script> <?php $toto=get_category(57)->category_count; ?> <div class="slider slider-nav text-center"> <?php $ii=1; $tmp_post = $post; $args = array( 'posts_per_page' => 8, 'offset'=> 0, 'category' => 57, 'order' =>'ASC' ); $myposts = get_posts( $args ); foreach( $myposts as $post ){ setup_postdata($post); ?> <div class="box-vib box-vib<?php echo $ii;?>" onclick="tostop()"> <div class="box-vib-music"> </div> <div class="box-vib-nam"> <?php the_field('name_audio'); ?> </div> </div> <?php } ?> </div>
修复方案
1. 先判断window.play有效性再调用stop
错误根源是window.play还未被赋值(比如页面首次点击音频项时,toknown函数还没执行过)就调用了stop()方法。修改tostop函数,增加判断逻辑:
function tostop() { // 先确认window.play存在且拥有stop方法 if (window.play && typeof window.play.stop === 'function') { window.play.stop(); } }
2. 确保Wavesurfer实例正确传递给window.play
你需要在每个音频项对应的Wavesurfer实例初始化完成后,调用toknown函数把实例传递过去。示例代码如下:
document.querySelectorAll('.box-vib-music').forEach((container) => { const wavesurfer = WaveSurfer.create({ container: container, // 你的其他配置项,比如waveColor、progressColor等 }); // 加载当前音频文件,替换为你的音频URL wavesurfer.load(container.parentElement.dataset.audioUrl); // 绑定点击事件:先停旧音频,再播放当前 container.parentElement.addEventListener('click', () => { tostop(); toknown(wavesurfer); wavesurfer.play(); }); });
3. 补充HTML的音频URL数据
在PHP循环输出的box-vib标签中,添加音频URL的自定义属性,方便JS获取:
<div class="box-vib box-vib<?php echo $ii;?>" data-audio-url="<?php the_field('audio_url'); ?>"> <!-- 原有内容 --> </div>
内容的提问来源于stack exchange,提问作者Enrize
相关产品推荐
相关产品推荐

