【问题标题】:React Native Expo Audio | Play live stream from latest positionReact Native Expo 音频 |从最新位置播放直播
【发布时间】:2020-05-12 17:11:57
【问题描述】:

我正在使用 Expo Audio 为我正在为在线广播制作的应用程序编写音频播放器。 音频来自在线直播,我已经成功添加了播放器以及与之相关的所有内容;但是,我遇到的一个问题是,如果我在继续播放音频时暂停音频,则音频将从暂停时继续播放,而不是从当前位置继续播放,我需要暂停并再次播放以使其更新到当前正在播放的内容。 我用 playAsync() 播放它,我试过用 pauseAsync()、stopAsync()、setStatusAsync({ shouldPlay: false, positionMillis: 0 });

关于如何让它以应有的方式工作的任何提示?

这是我用于音频播放器的代码,它是一个类,然后我创建一个实例以便能够从应用程序的不同位置对其进行管理:

class audioPlayer {
  static instance = null;
  static createInstance() {
    var object = new audioPlayer();
    return object;
  }

  _radioStream;

  /**
   * @returns {audioPlayer}
   */
  static getInstance() {
    if (audioPlayer.instance == null) {
      audioPlayer.instance = audioPlayer.createInstance();
    }

    return audioPlayer.instance;
  }

  // Call this first to create a new audio element
  createAudio() {
    this._radioStream = new Audio.Sound();
  };

  async loadAudioAsync() {
    try {
      await this._radioStream.loadAsync(
        { uri: "radio straem"},
      );
      store.dispatch(setLiveState(true));

      this.toggleAudio(); // Autoplay at start

      return true;
    } catch (error) {
      if (error.code === "E_LOAD_ERROR") {
        // In the case of an error we try to load again
        setTimeout(this.loadAudioAsync, 10000);

        throw new Error(error.code);
      } else {
        throw new Error(error);
      };
    };
  };

  async unloadAudioAsync() {
    await this._radioStream.unloadAsync();
  };

  async getStatusAsync() {
    return await this._radioStream.getStatusAsync();
  };

  async toggleAudio() {
    // We're gonna play or pause depending on the status
    let { isLoaded, isPlaying } = await this._radioStream.getStatusAsync();

    // If the user presses the audio and the stream connection has been lost or something
    // we try to load it again
    if (!isLoaded) {
      let res = await this.loadAudioAsync(); // Try to loadAudio again
      if (res) this.toggleAudio(); // Retrigger the toggle to start playing
    }

    if (isLoaded && !isPlaying) {
      store.dispatch(setPlayingStatus(true));
      await this._radioStream.playAsync();
    } else if (isLoaded && isPlaying) {
      store.dispatch(setPlayingStatus(false));
      await this._radioStream.setStatusAsync({ shouldPlay: false, positionMillis: 0 });
    };
  };
};

【问题讨论】:

  • 有解决办法吗?

标签: react-native audio expo


【解决方案1】:

我刚刚遇到了同样的问题(对于我的网络收音机https://notylus.fr)。 看来我找到了解决方案:而不是使用

playbackInstance.pauseAsync()

我现在用

playbackInstance.stopAsync()

对于游戏部分,我添加

等待播放实例.playAsync() //播放流 PlaybackInstance.setPositionAsync(0) //确保你在位置 0

最后

问候,

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2022-08-10
    相关资源
    最近更新 更多