Skip to content

Instantly share code, notes, and snippets.

@Charpell
Created July 7, 2019 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Charpell/449eae2e8bc49fcfa20afd16d79013ff to your computer and use it in GitHub Desktop.
Save Charpell/449eae2e8bc49fcfa20afd16d79013ff to your computer and use it in GitHub Desktop.
import { Alert } from "react-native";
import { Audio } from "expo";
export default class MusicPlayer {
// Current item index
index = 0;
constructor(list, initialState = { speed: 1, autoPlay: true }) {
// Create new object from Expo.Audio.Sound
this.soundObject = new Audio.Sound();
// Set speed value
this.speed = initialState.speed;
this.list = list;
}
/**
* Start or stop audio.
* @param {number} index - Index of playing item.
* @param {boolean} playing - Is audio playing now or no.
* @return {Promise}
*/
startPlay = async (index = this.index, playing = false) => {
const path = this.list[index].path;
this.index = index;
// Checking if now playing music, if yes stop that
if(playing) {
await this.soundObject.stopAsync();
} else {
// Checking if item already loaded, if yes just play, else load music before play
if(this.soundObject._loaded) {
await this.soundObject.playAsync();
} else {
await this.soundObject.loadAsync(path);
await this.soundObject.playAsync();
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment