P5.js实现点击随机播放歌曲功能遇阻求助
P5.js点击切换随机歌曲报错修复
问题根源
- 变量作用域冲突:全局声明的
sound未被正确赋值,setup函数内用let sound定义了局部变量,导致全局sound始终为undefined,触发Cannot read properties of undefined (reading 'isPlaying')错误。 - Playlist存储错误:数组中存储的是字符串
sound1/sound2/sound3,而非loadSound加载得到的声音对象,无法调用声音相关方法。 - 逻辑不符合需求:仅在初始化时选择一次随机歌曲,点击仅做播放/暂停操作,未实现“每次点击切换新随机歌曲”的要求。
修正后的代码
let currentSound; let amplitude; let playlist = []; function preload(){ // 加载声音并直接存入playlist数组 playlist.push(loadSound('taptwice.mp3')); playlist.push(loadSound('juniper.mp3')); playlist.push(loadSound('eyelids.mp3')); } function setup() { let cnv = createCanvas(windowWidth, windowHeight); cnv.mouseClicked(toggleSound); amplitude = new p5.Amplitude(); // 初始化时随机选一首 currentSound = getRandomSound(); } // 封装随机获取歌曲的函数 function getRandomSound() { return playlist[Math.floor(Math.random() * playlist.length)]; } function toggleSound() { // 先停止当前播放的歌曲(如果有的话) if (currentSound.isPlaying()) { currentSound.stop(); } // 切换新的随机歌曲并播放 currentSound = getRandomSound(); currentSound.play(); }
关键修改说明
- 全局维护
currentSound变量存储当前选中的声音对象,避免作用域问题。 playlist直接存储加载后的声音对象,而非字符串,确保能调用声音方法。- 封装
getRandomSound函数统一处理随机选曲逻辑,代码更清晰。 - 修改
toggleSound逻辑:停止当前歌曲后切换新曲并播放,实现每次点击切换新歌的需求。
内容的提问来源于stack exchange,提问作者nholder88
相关产品推荐
相关产品推荐

