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

Expo-AV 如何按随机数播放对应歌曲?优化playSound函数

解决方法

你的playSound函数已经支持传入audioFile参数,完全可以通过这个参数轻松切换不同的MP3文件,具体操作如下:

1. 建立数字与音频文件的映射

首先创建一个映射关系,让1-99的数字对应到各自的音频文件路径。假设你的音频文件按1.mp3、2.mp3...99.mp3的规则命名,存放在指定目录下:

// 对象映射:键为数字,值为音频文件路径
const soundMap = {};
for (let i = 1; i <= 99; i++) {
  soundMap[i] = `../assets/sounds/${i}.mp3`; // 根据你的实际文件路径调整
}

// 或者使用数组:索引+1对应数字(数组从0开始)
const soundArray = Array.from({length: 99}, (_, index) => `../assets/sounds/${index + 1}.mp3`);

2. 随机生成数字并调用playSound

生成1-99的随机数后,从映射中取出对应音频路径,传入playSound即可:

// 生成1到99的随机数
const randomNumber = Math.floor(Math.random() * 99) + 1;

// 使用对象映射调用
playSound(soundMap[randomNumber]);

// 或者使用数组调用(注意数组索引要减1)
playSound(soundArray[randomNumber - 1]);

3. 可选:优化playSound函数

如果需要避免重复创建音频实例、处理正在播放的音频,可以对原函数做简单优化:

async function playSound(audioFile) {
  console.log('Loading Sound');
  // 若当前有播放中的音频,先停止并卸载
  if (sound) {
    await sound.stopAsync();
    await sound.unloadAsync();
  }
  const { sound: newSound } = await Audio.Sound.createAsync(require(audioFile));
  setSound(newSound);
  await newSound.playAsync();
}

内容的提问来源于stack exchange,提问作者Yann Fouquet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:14:53