Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.********.surfaceviewtest.Audio;
- import android.content.Context;
- import android.content.res.AssetFileDescriptor;
- import android.content.res.AssetManager;
- import android.media.MediaPlayer;
- import android.media.SoundPool;
- import android.util.Log;
- import java.io.IOException;
- public class Audio {
- public static Context context;
- static AssetManager am;
- static SoundPool sp;
- public static MediaPlayer mediaPlayer;
- public static boolean mediaPaused = false;
- /**
- * Create a new music player from a filepath.
- * MediaPlayer object returned is already prepared to be played
- *
- * @param file The filepath for the sound file to be streamed
- * @return reference to the Audio class MediaPlayer object
- */
- public static MediaPlayer createMusic(String file) {
- // Create new instance if necessary - prevents resource usage
- if (mediaPlayer == null) {
- mediaPlayer = new MediaPlayer();
- }
- if (am == null) {
- am = context.getAssets();
- }
- try {
- AssetFileDescriptor asset = am.openFd(file);
- mediaPlayer.setDataSource(asset.getFileDescriptor(), asset.getStartOffset(), asset.getLength());
- mediaPlayer.prepare();
- } catch (IOException e) {
- Log.e("AudioClass", "createMusic: Unable to open media from String. File not available");
- }
- return mediaPlayer;
- }
- // Release and nullify the media player to free up resources
- public static void unloadMusic() {
- if (mediaPlayer == null) {
- return;
- }
- if (mediaPlayer.isPlaying()) {
- mediaPlayer.stop();
- }
- mediaPlayer.release();
- mediaPlayer = null;
- }
- public static void onStop(boolean isFinishing) {
- // TODO Close all instanced Audio objects in Audio.onStop()
- if ((mediaPlayer != null && mediaPlayer.isPlaying()) || mediaPaused) {
- mediaPlayer.pause();
- if (isFinishing) {
- Audio.unloadMusic();
- }
- }
- }
- public static void onPause() {
- if (mediaPlayer != null && mediaPlayer.isPlaying()) {
- mediaPaused = true;
- mediaPlayer.pause();
- }
- }
- public static void onResume() {
- if (mediaPlayer != null && mediaPaused) {
- mediaPlayer.start();
- mediaPaused = false;
- }
- }
- public static void setMediaPaused(boolean pause) {
- if (pause) {
- onPause();
- } else {
- onResume();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment