You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

P5.js实现点击随机播放歌曲功能遇阻求助

P5.js点击切换随机歌曲报错修复

问题根源

  1. 变量作用域冲突:全局声明的sound未被正确赋值,setup函数内用let sound定义了局部变量,导致全局sound始终为undefined,触发Cannot read properties of undefined (reading 'isPlaying')错误。
  2. Playlist存储错误:数组中存储的是字符串sound1/sound2/sound3,而非loadSound加载得到的声音对象,无法调用声音相关方法。
  3. 逻辑不符合需求:仅在初始化时选择一次随机歌曲,点击仅做播放/暂停操作,未实现“每次点击切换新随机歌曲”的要求。

修正后的代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:30:01