如何修改JavaScript代码实现点击不同图片播放对应MP3音效
解决点击不同图片播放对应音效的问题
你只需要把play函数改成接收音频路径参数的形式,就能复用同一个函数处理不同图片的音效播放需求,具体修改如下:
1. 重构play函数
让函数接受一个soundPath参数,动态创建对应路径的音频实例:
function play(soundPath) { const audio = new Audio(soundPath); audio.play(); }
2. 给每个img标签传入对应音频路径
在onclick事件里调用play时,直接传入该图片对应的MP3文件路径即可:
<img onclick="play('sounds/apple.mp3')" src="images/apple.png" width="400" height="400" /><br /> <img onclick="play('sounds/orange.mp3')" src="images/orange.png" width="400" height="400" /><br /> <img onclick="play('sounds/pear.mp3')" src="images/pear.png" width="400" height="400" /><br />
可选优化:避免同时播放多个音频
如果不想让多个音频同时播放,可以维护一个全局的音频实例,每次播放前暂停上一个:
let currentAudio = null; function play(soundPath) { // 暂停并重置当前播放的音频 if (currentAudio) { currentAudio.pause(); currentAudio.currentTime = 0; } currentAudio = new Audio(soundPath); currentAudio.play(); }
内容的提问来源于stack exchange,提问作者topdoller
相关产品推荐
相关产品推荐

