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

iOS端Expo应用后台/锁屏状态下音频无法持续播放问题

iOS后台音频播放故障排查与修复

问题概况

执行eas build --profile preview --platform ios构建应用并安装至iPhone 12 Mini后,关闭应用或锁屏时音频立即停止播放;重新打开应用,音频瞬间恢复。已在app.json中配置iOS后台音频权限:

"ios": {
      "supportsTablet": true,
      "bundleIdentifier": "com.rahlok.pplay",
      "infoPlist": {
        "UIBackgroundModes": [
          "audio"
        ]
      }
    },

核心播放组件Player.js代码如下:

import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function Player() {
  const [sound, setSound] = React.useState();

  React.useEffect(() => {
    Audio.setAudioModeAsync({
      staysActiveInBackground: true,
    });
  })

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

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

  async function pauseSound() {
    console.log('Pausing Sound');
    await sound.pauseAsync();
  }

  async function resumeSound() {
    console.log('Resuming Sound');
    await sound.playAsync();
  }

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

  return (
    <View>
      <Button title="Play Sound" onPress={playSound} />
      <Button title="Pause Sound" onPress={pauseSound} />
      <Button title="Resume Sound" onPress={resumeSound} />
    </View>
  );
}

修复方案

1. 完善音频模式配置

当前音频模式仅设置了staysActiveInBackground,缺少iOS后台播放必需的其他参数补充,且未正确处理异步逻辑。修改音频模式初始化代码:

React.useEffect(() => {
  const setupAudioMode = async () => {
    await Audio.setAudioModeAsync({
      staysActiveInBackground: true,
      interruptionModeIOS: Audio.InterruptionModeIOS.DoNotMix,
      playsInSilentModeIOS: true,
      playThroughEarpieceAndroid: false,
      shouldDuckAndroid: false,
    });
  };
  setupAudioMode();
}, []);
  • 添加空依赖数组,避免组件重复渲染时反复调用配置方法
  • 明确设置iOS端中断模式、静音播放权限,同时补充Android端必填属性(Expo Audio要求全平台属性声明)

2. 为音频实例开启后台播放权限

创建Sound实例时,需显式指定shouldPlayInBackground参数为true:

async function playSound() {
  console.log('Loading Sound');
  const { sound } = await Audio.Sound.createAsync(
    require('../assets/demo.mp3'),
    { shouldPlayInBackground: true }
  );
  setSound(sound);

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

3. 清理缓存重新构建

避免旧构建缓存导致配置不生效,执行带清缓存的构建命令:

eas build --profile preview --platform ios --clear-cache

验证场景

修改完成后重新安装应用,测试以下场景:

  • 播放音频后锁屏,确认音频持续播放
  • 播放音频后切换至其他应用,确认音频持续播放

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:00:57