reactjs 暂停react native expo Audio?

wb1gzix0  于 2023-10-17  发布在  React
关注(0)|答案(2)|浏览(143)

我没有问题运行音频,但我有麻烦暂停它。如果有人能帮忙,那就太好了。

async function playMusic() {
  const soundObject = new Audio.Sound();
  console.log("Being hit")

  try {
    await soundObject.loadAsync({uri:'https://firebasestorage.googleapis.com/v0/b/o/myFolder%2FMello%20C%20-%20Easy.mp3?c4e-4bf8-b8ea-dcc201efff44'});
    await soundObject.playAsync();
  } catch (error) {
    alert("Error" + error.message)
  }
}

async function stopMusic() {
  console.log("Not Being hit")
 const soundObject = new Audio.Sound();

 try {
   await soundObject.loadAsync({uri:'https://firebasestorage.googleapis.com/v03?alt=media&token=e44f7b2f-8c4e-4bf8-b8ea-dcc201efff44'});
   await soundObject.stopAsync();
 } catch (error) {
   alert("Error" + error.message)
 }
}
zaqlnxep

zaqlnxep1#

我们永远不应该把Sound示例创建为状态变量。因为只要有重新渲染,它就会重新渲染声音示例。
您应该创建一个ref变量并使用它,

const sound = React.useRef(new Audio.Sound());

Working Example
播放音乐/Play Music

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

const SampleTrack = require('./Roses.m4a');

export default function App() {
  const [Loaded, SetLoaded] = React.useState(false);
  const [Loading, SetLoading] = React.useState(false);
  const sound = React.useRef(new Audio.Sound());

  React.useEffect(() => {
    LoadAudio();
  }, []);

  const PlayAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === false) {
          sound.current.playAsync();
        }
      }
    } catch (error) {}
  };

  const PauseAudio = async () => {
    try {
      const result = await sound.current.getStatusAsync();
      if (result.isLoaded) {
        if (result.isPlaying === true) {
          sound.current.pauseAsync();
        }
      }
    } catch (error) {}
  };

  const LoadAudio = async () => {
    SetLoading(true);
    const checkLoading = await sound.current.getStatusAsync();
    if (checkLoading.isLoaded === false) {
      try {
        const result = await sound.current.loadAsync(SampleTrack, {}, true);
        if (result.isLoaded === false) {
          SetLoading(false);
          console.log('Error in Loading Audio');
        } else {
          SetLoading(false);
          SetLoaded(true);
        }
      } catch (error) {
        console.log(error);
        SetLoading(false);
      }
    } else {
      SetLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.AudioPLayer}>
        {Loading ? (
          <ActivityIndicator size={'small'} color={'red'} />
        ) : (
          <>
            {Loaded === false ? (
              <>
                <ActivityIndicator />
                <Text>Loading Song</Text>{' '}
              </>
            ) : (
              <>
                <Button title="Play Song" onPress={PlayAudio} />
                <Button title="Pause Song" onPress={PauseAudio} />
              </>
            )}
          </>
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  AudioPLayer: {
    width: '100%',
    height: 50,
    alignItems: 'center',
  },
});
jtw3ybtb

jtw3ybtb2#

对于那些仍然在这个问题上挣扎的人,你可以使用Expo提供的视频组件运行一个音频轨道。从那里你会有一个本地控制部分播放/停止音轨

相关问题