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

求助:如何使用Expo-AV实现3个音频文件依次连续播放?

使用Expo-AV依次播放多个音频文件的实现方案

可以通过维护音频文件队列、监听单音频播放结束事件来自动触发下一个音频播放,以下是具体实现代码和关键说明:

核心实现代码(React Native + Expo)

import { useState, useRef, useEffect } from 'react';
import { Audio } from 'expo-av';

const SequentialAudioPlayer = () => {
  // 替换为你的实际音频文件路径,支持本地资源或远程URL
  const audioQueue = useRef([
    require('./audio1.mp3'),
    require('./audio2.mp3'),
    require('./audio3.mp3')
  ]);
  const soundInstance = useRef(null);
  const [currentTrackIndex, setCurrentTrackIndex] = useState(0);

  // 加载并播放队列中的下一个音频
  const loadNextTrack = async () => {
    // 释放当前音频资源,避免内存泄漏
    if (soundInstance.current) {
      await soundInstance.current.unloadAsync();
    }

    // 所有音频播放完毕,重置索引或执行收尾逻辑
    if (currentTrackIndex >= audioQueue.current.length) {
      setCurrentTrackIndex(0);
      return;
    }

    try {
      const { sound } = await Audio.Sound.createAsync(
        audioQueue.current[currentTrackIndex],
        { shouldPlay: true }
      );
      soundInstance.current = sound;

      // 监听播放状态,结束时自动切换下一首
      sound.setOnPlaybackStatusUpdate(status => {
        if (status.didJustFinish) {
          setCurrentTrackIndex(prev => prev + 1);
        }
      });
    } catch (err) {
      console.error('音频加载失败:', err);
    }
  };

  // 索引变化时触发下一首播放,初始加载第一首
  useEffect(() => {
    loadNextTrack();

    // 组件卸载时清理资源
    return () => {
      if (soundInstance.current) {
        soundInstance.current.unloadAsync();
      }
    };
  }, [currentTrackIndex]);

  return null; // 可根据需求添加播放控制UI(开始/暂停按钮等)
};

export default SequentialAudioPlayer;

关键细节说明

  • 队列管理:audioQueue维护待播放的音频列表,支持本地资源(require引入)或远程音频URL(直接传入字符串)。
  • 状态监听:通过setOnPlaybackStatusUpdate监听播放状态,当didJustFinish为true时,自动切换到下一个音频索引。
  • 资源清理:每次切换音频时卸载当前资源,组件卸载时也执行清理操作,避免内存占用过高。
  • 手动控制扩展:如果需要添加播放/暂停控制,可直接调用soundInstance.current.playAsync()或soundInstance.current.pauseAsync()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:33:29