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

React Native Expo-AV在iPhone上无法播放音频的问题求助

问题

参考Expo官方音频示例代码,仅替换MP3文件路径后,在iPhone上无法播放音频。程序未崩溃,仅打印加载和播放日志但无声音。

使用的代码(已添加必要import):

const [sound, setSound] = useState();

async function playSound() {
  console.log('Loading Sound');
  const { sound } = await Audio.Sound.createAsync(
    require('./path/to/my/file.mp3'));
  setSound(sound);

  console.log('Playing Sound');
  await sound.playAsync();
}

useEffect(() => {
  return sound
    ? () => {
        console.log('Unloading Sound');
        sound.unloadAsync();
      }
    : undefined;
}, [sound]);

打印日志:

LOG  Loading Sound
LOG  Playing Sound

相关依赖版本:

"@react-navigation/native": "^6.1.7",
"@react-navigation/native-stack": "^6.9.13",
"expo": "~48.0.18",
"expo-av": "~13.2.1",
"react": "18.2.0",
"react-native": "0.71.8",
解决方案
  • 检查音频文件兼容性
    iPhone对MP3编码有严格要求,确保你的音频是标准MPEG-1 Layer 3编码,比特率在8-320kbps之间。可以用Audacity等工具重新导出符合标准的MP3文件后测试。

  • 添加iOS音频权限配置
    在app.json或app.config.js中补充iOS权限声明,确保App能正常访问音频功能:

    "ios": {
      "infoPlist": {
        "NSMicrophoneUsageDescription": "应用需要音频权限以播放媒体内容",
        "UIBackgroundModes": ["audio"] // 如需后台播放则添加此项
      }
    }
    

    注意权限描述需符合App实际用途,避免影响审核。

  • 捕获音频加载错误
    修改代码添加错误捕获,排查是否是文件加载环节出问题:

    async function playSound() {
      console.log('Loading Sound');
      try {
        const { sound, status } = await Audio.Sound.createAsync(
          require('./path/to/my/file.mp3'),
          { shouldPlay: false }
        );
        if (!status.isLoaded) {
          console.error('音频加载失败:', status.error);
          return;
        }
        setSound(sound);
        console.log('Playing Sound');
        await sound.playAsync();
      } catch (error) {
        console.error('音频实例创建失败:', error);
      }
    }
    

    通过日志可以定位具体错误,比如文件路径错误、文件损坏等。

  • 检查系统音频设置
    确认iPhone未开启侧边静音开关,媒体音量已调高,且App未被系统静音(播放时按音量键可快速检查)。

  • 验证本地文件路径
    iOS文件系统区分大小写,确保require中的路径和文件名完全匹配,文件确实存在于指定位置。可以尝试将MP3放在项目根目录,用require('./file.mp3')简化测试。

  • 用远程音频测试
    暂时替换本地文件为公开远程MP3地址(如{ uri: 'https://example.com/test.mp3' }),如果远程音频能正常播放,说明本地文件本身或路径存在问题。

内容的提问来源于stack exchange,提问作者Ferran Maylinch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:12:54