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

React Native Expo-AV:如何设置音频循环播放特定时长后停止

实现Expo AV音频循环播放特定时长后自动停止

嘿,这个需求完全能搞定!我之前做项目时遇到过类似场景,给你分享具体的实现思路和代码:

核心思路

我们可以结合setTimeout定时器和Expo AV提供的setIsLoopingAsync、stopAsync方法来实现:

  1. 页面加载时启动循环播放的音频
  2. 设置一个与目标播放时长一致的定时器
  3. 定时器触发后,先关闭音频循环,再停止播放
  4. 别忘了在组件卸载时清理定时器和音频资源,避免内存泄漏

完整代码示例

import { Audio } from 'expo-av';
import { useEffect, useState } from 'react';
import { View, Text } from 'react-native';

export default function BackgroundMusicScreen() {
  const [soundInstance, setSoundInstance] = useState(null);
  // 定义目标播放时长,这里以3分钟为例,单位是毫秒
  const TARGET_PLAY_DURATION = 180000;

  // 初始化并播放音频
  async function initAndPlaySound() {
    try {
      const { sound } = await Audio.Sound.createAsync(
        // 替换成你的音频文件路径
        require('./assets/background-track.mp3'),
        { isLooping: true, volume: 0.5 } // 可根据需求调整音量
      );
      setSoundInstance(sound);
      await sound.playAsync();
    } catch (error) {
      console.error('播放音频出错:', error);
    }
  }

  useEffect(() => {
    // 启动音频播放
    initAndPlaySound();

    // 设置定时器,到点后停止循环并结束播放
    const playbackTimer = setTimeout(async () => {
      if (soundInstance) {
        // 先关闭循环,确保音频不会继续重复
        await soundInstance.setIsLoopingAsync(false);
        // 停止播放
        await soundInstance.stopAsync();
      }
    }, TARGET_PLAY_DURATION);

    // 组件卸载时的清理逻辑
    return async () => {
      if (soundInstance) {
        // 卸载音频资源,彻底释放内存
        await soundInstance.unloadAsync();
      }
      // 清除定时器,避免内存泄漏
      clearTimeout(playbackTimer);
    };
  }, []);

  return (
    // 你的页面UI内容
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>页面内容</Text>
    </View>
  );
}

额外注意事项

  • 错误处理:建议给音频操作加上try/catch,避免因音频文件路径错误或权限问题导致崩溃
  • 用户交互中断:如果用户在播放过程中切换页面或退出应用,清理函数会自动处理资源释放;如果需要支持手动暂停/继续,可以扩展对应的交互逻辑
  • 时长精度:setTimeout的精度受JS事件循环影响,偏差通常在几十毫秒内,对于背景音乐场景完全够用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:52:37