expo install expo-av
json
import { Audio } from "expo-av"
app
expo-audio-arguments-documentation
要麼直接默認不配置,要麼則全部配置都寫上,不然會報錯。async
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(); } ); };