Skip to content

Instantly share code, notes, and snippets.

@ironyee
Last active February 21, 2019 12:18
Show Gist options
  • Save ironyee/7b3432b8c846b671c25c232782c4e6be to your computer and use it in GitHub Desktop.
Save ironyee/7b3432b8c846b671c25c232782c4e6be to your computer and use it in GitHub Desktop.
import { StatusBar } from 'react-native';
import { Audio, FileSystem } from 'expo';
export default class CachedAudio {
constructor(uri) {
this.uri = uri;
this.fileUri = null;
this.sound = null;
this.downloadResumable = null;
}
async _downloadAsync() {
this.fileUri = `${FileSystem.cacheDirectory}${encodeURIComponent(encodeURIComponent(this.uri))}`;
const { exists } = await FileSystem.getInfoAsync(this.fileUri);
if (exists) {
return;
}
this.downloadResumable = FileSystem.createDownloadResumable(
this.uri,
this.fileUri,
);
StatusBar.setNetworkActivityIndicatorVisible(true);
try {
const { uri } = await this.downloadResumable.downloadAsync();
this.fileUri = uri;
this.downloadResumable = null;
} finally {
StatusBar.setNetworkActivityIndicatorVisible(false);
}
}
async _createAsync() {
const { sound } = await Audio.Sound.create({ uri: this.fileUri });
this.sound = sound;
}
async playAsync() {
if (!this.fileUri) {
await this._downloadAsync();
}
if (!this.sound) {
await this._createAsync();
}
const { positionMillis, durationMillis } = await this.sound.getStatusAsync();
if (positionMillis === durationMillis) {
await this.sound.replayAsync();
} else {
await this.sound.playAsync();
}
return this.sound;
}
async pauseAsync() {
if (!this.sound) {
return;
}
await this.sound.pauseAsync();
}
async unloadAsync() {
if (this.downloadResumable) {
await this.downloadResumable.pauseAsync();
}
if (this.sound) {
this.sound.setOnPlaybackStatusUpdate(null);
await this.sound.unloadAsync();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment