乐趣区

expo-使用audio

expo 使用 audio

完整文档

Documentation

install

expo install expo-av

import

import {Audio} from "expo-av"

option

expo-audio-arguments-documentation
要么直接默认不配置,要么则所有配置都写上,否则会报错。

constructor(props) {super(props);
  this.state = {
    // 配置你的歌曲 url,或者动态获取
    songUrl: "",
    isPlaying: false
  };

  this.soundObject = null;
  const mode = {
    playsInSilentModeIOS: true,
    allowsRecordingIOS: false,
    staysActiveInBackground: true,
    interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
    // 前四个配置有一定的固定搭配,详见上面文档链接
    interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX,
    shouldDuckAndroid: true,
    playThroughEarpieceAndroid: false
  };
  Audio.setAudioModeAsync(mode);
}

IOS 后台播放还需要配置下 app.json

{
  "expo": {
    ...
    "ios": {
      ...
      "infoPlist": {
        ...
        "UIBackgroundModes": ["audio"]
      }
    }
  }
}

使用

componentDidUpdate(preProps, preState) {
  // flac 播放会失败,其他格式未测试
  if (preState.songUrl !== this.state.songUrl && !/^.*?\.mp3$/.test(this.state.songUrl)) {this.loadAudio();
  }
}

// 加载
async loadAudio() {this.soundObject = new Audio.Sound();
  try {
    await this.soundObject.loadAsync({uri: this.state.songUrl});
    // 自动播放
    await this.soundObject.playAsync();
    this.setState({isPlaying: true});
  } catch (error) {console.warn("ERROR LOADING AUDIO:", error);
  }
}

// 播放 / 暂停
toggleAudioPlayStatus = () => {if (!/^.*?\.mp3$/.test(this.state.songUrl)) return;
  this.setState(
    {isPlaying: !this.state.isPlaying},
    () => {this.state.isPlaying ? this.soundObject.playAsync() : this.soundObject.pauseAsync();}
  );
};
退出移动版