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

使用expo-av的Audio在定时器中播放39次后意外停止求助

问题原因

你每次在setInterval里调用Audio.Sound.createAsync都会创建一个新的音频实例,但Expo AV对同时存在的音频实例数量有默认限制(约40个),当创建到第39个后,无法再生成新实例,音频自然无法播放,但定时器不受实例限制,仍会持续输出日志。

解决方案

不要每次循环都创建新音频实例,提前初始化一次,之后循环里仅调用播放方法即可,同时记得在组件销毁时清理资源:

import { useEffect, useRef } from 'react';
import { Audio } from 'expo-av';
import audioFile from "./assets/audios/sound.mp3";

export default function YourComponent() {
  const soundRef = useRef(null);
  const intervalRef = useRef(null);

  useEffect(() => {
    // 初始化音频实例
    const initSound = async () => {
      const { sound } = await Audio.Sound.createAsync(audioFile);
      soundRef.current = sound;
      
      // 设置循环播放定时器
      intervalRef.current = setInterval(async () => {
        // 重置播放位置到开头,避免音频未播完就重复播放的叠加问题
        await soundRef.current.replayAsync();
        console.log("Inside interval");
      }, 1000);
    };

    initSound();

    // 组件卸载时清理资源
    return () => {
      soundRef.current?.unloadAsync();
      intervalRef.current && clearInterval(intervalRef.current);
    };
  }, []);

  return (
    // 你的组件内容
  );
}
额外提示
  • 使用replayAsync替代playAsync,能确保每次播放都从音频起始位置开始,避免音频时长超过1秒时多次播放叠加的问题。
  • 用useRef保存音频实例和定时器引用,方便在清理函数中访问操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:35:57