点击其他音频链接时停止当前播放音频的实现求助
解决点击新音频链接时停止当前播放的问题
你的问题核心在于:你通过new Audio()动态创建音频实例,而非页面内的<audio>标签,所以之前用document.getElementsByTagName('audio')的监听代码无法捕获这些动态实例,自然起不到停止播放的作用。
修复方案
- 定义一个全局变量,专门保存当前正在播放的音频实例
- 每次播放新音频前,先检查该变量是否存在有效实例,若有则暂停它
- 创建新音频实例并播放,同时更新全局变量指向新实例
修改后的完整代码
<div id="myDIV1" style="display: block;"> <img src="newMuslims/images/SurahAl_Fatiha.jpg" width="555" height="1001" usemap="#image-map" onDblClick="imgResize(this)"> <map name="image-map"> <area title="Aya0" href="javascript:MyAudio(0);" coords="-5,66,553,116" shape="rect"> <area title="Ayah1" href="JavaScript:MyAudio(1);" coords="2,117,555,197" shape="rect"> <area title="Ayah2" href="JavaScript:MyAudio(2);" coords="0,199,553,277" shape="rect"> <area title="Ayah3" href="JavaScript:MyAudio(3);" coords="0,279,552,356" shape="rect"> <area title="Ayah4" href="JavaScript:MyAudio(4);" coords="-1,358,551,481" shape="rect"> <area title="Ayah5" href="JavaScript:MyAudio(5);" coords="-5,483,554,570" shape="rect"> <area title="Ayah6" href="JavaScript:MyAudio(6);" coords="1,573,553,663" shape="rect"> <area title="Ayah7" href="JavaScript:MyAudio(7);" coords="2,665,552,818" shape="rect"> <area title="ameen" href="JavaScript:MyAudio(8);" coords="1,820,554,913" shape="rect"> </map> <script> // 全局变量:跟踪当前正在播放的音频实例 let currentAudio = null; function MyAudio(n) { var soundfile1 = "https://wensite/audio/audioFile"; var fileExt = ".mp3"; // 暂停并重置当前音频(如果存在) if (currentAudio) { currentAudio.pause(); currentAudio.currentTime = 0; } // 生成目标音频文件路径 var soundfile = soundfile1.concat(n).concat(fileExt); // 创建新音频实例并播放 currentAudio = new Audio(soundfile); currentAudio.play(); } </script>
额外优化提示
你原代码中的for循环是无效冗余代码,它循环生成文件名但最终被覆盖,没有实际作用,可以直接删除。
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

