Expo-Av 一次播放多个声音

时间:2021-04-24 12:17:13

标签: react-native expo expo-av

我试图让多个声音文件在 Expo-AV 上播放,但是当一个声音播放时,另一个停止。我一次只能播放一种声音。

我的尝试

我每次都尝试了一个类方法来创建一个不同的实例,但是没有用。所以我回到功能组件并调用 playSound() 同时播放但它不起作用

这是我的代码:

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

const MusicModal = (props) => {
  const [sound, setSound] = React.useState(new Audio.Sound());
  const [isPlaying, setIsPlaying] = React.useState(false);
  
  useEffect(()=>{
      handleAudioConfig()
},[])

async function playSound(song) {
  console.log('Loading Sound');
  const { sound } = await Audio.Sound.createAsync(song);
  setSound(sound);
  sound.setIsLoopingAsync(true)
  console.log('Playing Sound');
  await sound.playAsync().then(()=>{
  setIsPlaying(true)
}); 
}

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

}, [sound]);

const handleAudioConfig = async() =>{
  try {
    await Audio.setAudioModeAsync({
      allowsRecordingIOS: false,
      interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
      playsInSilentModeIOS: true,
      interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX,
      shouldDuckAndroid: true,
      staysActiveInBackground: true,
      playThroughEarpieceAndroid: false,
  
    })
    playSound(require('soundFilePath'))
    playSound(require('soundFilePath'))
  } catch (e) {
    console.log(e)
  }  
}

  return (
      <View>
          <Text>Play Sound</Text>
    </View>
  );
};

export default MusicModal;

1 个答案:

答案 0 :(得分:0)

您可以改用 Video 组件,

import { Video } from "expo-av";


...

const nodeRef = useRef();

async function playSound(song) {
  console.log('Playing Sound');
  await nodeRef.current?.playAsync().then(()=>{
  setIsPlaying(true)
}); 
}

...

return (
    <View>
          <Text>Play Sound</Text>
          <Video
           ref={nodeRef}
           source={song}
           style={{opacity:0,zIndex:-1}} // in case you want the same UI 
           isLooping
         />
    </View>
  );