【问题标题】:Stop Current Sound when another is pressed React Native Expo按下另一个时停止当前声音 React Native Expo
【发布时间】:2021-06-22 23:21:07
【问题描述】:

当按下另一个声音时,我在尝试停止当前播放的声音时遇到了麻烦,而不必在 react Native Expo 中暂停当前的声音。注意:我可以完美地暂停和播放声音。所以基本上就像一个普通的音乐播放器,如果按下另一首歌曲时重叠。


const SampleTrack = {uri:'https://firebasestorage.googleapisro-b97ec.appspot.com/o/song%201.mp3?a9'}

const FirstP = () => { 
  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);
    }
  };

如果有人可以提供帮助,那就太好了。

【问题讨论】:

  • 大概你有一个歌曲列表或类似的东西,但你没有包括它,所以很难做出好的推荐。我会将音频状态存储在所有单个列表项的父视图中,以便在按下新项时轻松播放/暂停。
  • 感谢您的帮助!

标签: reactjs react-native expo


【解决方案1】:

这是一个完整的音频播放器,具有播放/暂停/加载/下一个/上一个功能。

Working Example

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 Tracks = [
  {
    id: 0,
    track: require('./Roses.m4a'),
  },
  {
    id: 1,
    track: require('./Poison.m4a'),
  },
  {
    id: 2,
    track: require('./Alone.m4a'),
  },
];

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

  React.useEffect(() => {
    LoadAudio();

    return () => Unload();
  }, [CurrentSong]);

  const Unload = async () => {
    await sound.current.unloadAsync();
  };

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

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

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

  const NextSong = () => {
    if (CurrentSong.id === Tracks[Tracks.length - 1].id) {
      SetCurrentSong(Tracks[0]);
    } else {
      SetCurrentSong(Tracks[CurrentSong.id + 1]);
    }
  };

  const PrevSong = () => {
    if (CurrentSong.id === 0) {
      SetCurrentSong(Tracks[Tracks.length - 1]);
    } else {
      SetCurrentSong(Tracks[CurrentSong.id - 1]);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.AudioPLayer}>
        {Loading === true ? (
          <ActivityIndicator size={'small'} color={'red'} />
        ) : (
          <>
            <Button title="Play Song" onPress={PlayAudio} />
            <Button title="Pause Song" onPress={PauseAudio} />
            <Text>Currently Playing : {CurrentSong.id}</Text>
            <Button title="Next Song" onPress={NextSong} />
            <Button title="Previous Song" onPress={PrevSong} />
          </>
        )}
      </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',
  },
});

【讨论】:

  • 谢谢你,但你能帮我把每个声音与不同的按钮联系起来吗?我试图将它们用作道具,但没有任何帮助。我正在尝试做这样的事情。
  • 再次检查工作示例零食以查看您询问的结果。我已经更新了
  • 感谢您的帮助。我仍然对如何将某个按钮与我选择的任何歌曲相匹配感到有些困惑。就像如果我想让每首歌曲 id 与其自己的 playAudio 按钮匹配。就像一个播放列表有不同的歌曲,每个歌曲按钮都有自己的声音。
  • 我想出了一种方法,但我认为它不是正确的方法。它也给了我一个警告,让我改变 else 部分,所以它不一样,但它不起作用然后const ThirdSong = () =&gt; { if (CurrentSong.id === Tracks[Tracks.length - 1].id) { SetCurrentSong(Tracks[3]); } else { SetCurrentSong(Tracks[3]);} };
猜你喜欢
  • 2018-10-21
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多