Back to project page mclib.
The source code is released under:
Apache License, Version 2.0 FoundationProjectsPeopleGet InvolvedDownloadSupport ApacheHome ? Licenses Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITION...
If you think the Android project mclib listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
/* Copyright 2012 Mikhail Chabanov//from w ww. j a va2s . c o m Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mc.lib.audio; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import mc.lib.files.PermissionHelper; import mc.lib.interfaces.OnCompleteListener; import mc.lib.interfaces.OnProgressListener; import mc.lib.stream.StreamHelper; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnSeekCompleteListener; import android.net.Uri; import android.os.Handler; import android.util.Log; public class MediaAudioPlayer implements IAudioPlayer, OnPreparedListener, OnCompletionListener, OnErrorListener { private static final String LOGTAG = MediaAudioPlayer.class.getSimpleName(); protected static final long PROGRES_UPDATE_DELAY = 1000 / 24; private OnCompleteListener<Class<?>> completeListener; private AudioSource lastAudioSource = new AudioSource(); private OnProgressListener progressListener; private ProgressNotifier progressNotifier; private boolean disableStartPlay; private MediaPlayer mediaPlayer; private boolean preparing; private boolean repeat; private Handler handler; private Context context; private boolean paused; private int streamType; private int startPos; private class ProgressNotifier implements Runnable { private boolean stop; public void stop() { stop = true; handler.removeCallbacks(this); } @Override public void run() { if(progressListener != null && mediaPlayer.getCurrentPosition() > 0) { progressListener.notifyProgress(mediaPlayer.getCurrentPosition(), mediaPlayer.getDuration()); } if(!stop) { handler.postDelayed(this, PROGRES_UPDATE_DELAY); } else { progressNotifier = null; } } }; public MediaAudioPlayer(Context context) { this(context, AudioManager.STREAM_MUSIC); } public MediaAudioPlayer(Context context, int streamType) { super(); this.preparing = true; this.streamType = streamType; this.context = context.getApplicationContext(); } @Override public void play(int resId) { preparing = true; AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId); if(afd == null) { Log.e(LOGTAG, "Cannot open from res:" + resId); return; } play(afd); StreamHelper.close(afd); } @Override public void play(String filePath) { preparing = true; try { reset(); lastAudioSource.clear(); lastAudioSource.filePath = filePath; PermissionHelper.setEveryoneCanRead(filePath); mediaPlayer.setDataSource(filePath); mediaPlayer.setAudioStreamType(streamType); mediaPlayer.prepareAsync(); } catch(Exception e) { Log.e(LOGTAG, "Error on preparing track " + filePath, e); } } @Override public void play(File path) { play(path.getAbsolutePath()); } @Override public void play(Uri uri) { preparing = true; try { reset(); lastAudioSource.clear(); lastAudioSource.uri = uri; mediaPlayer.setDataSource(context, uri); mediaPlayer.setAudioStreamType(streamType); mediaPlayer.prepareAsync(); } catch(Exception e) { Log.e(LOGTAG, "Error on preparing track " + uri, e); } } @Override public void play(InputStream is) { preparing = true; String tmpFile; try { tmpFile = context.getCacheDir() + "/audio.tmp"; lastAudioSource.clear(); lastAudioSource.is = is; FileOutputStream fos = new FileOutputStream(tmpFile); StreamHelper.copyStream(is, fos); StreamHelper.close(fos); } catch(Exception e) { Log.e(LOGTAG, "Cannot create cache file.", e); return; } play(tmpFile); } @Override public void play(AssetFileDescriptor afd) { preparing = true; try { reset(); mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); mediaPlayer.setAudioStreamType(streamType); mediaPlayer.prepareAsync(); } catch(Exception e) { Log.e(LOGTAG, "Error on preparing track " + afd, e); } } @Override public void play(int resId, int startPos) { this.startPos = startPos; play(resId); } @Override public void play(String filePath, int startPos) { this.startPos = startPos; play(filePath); } @Override public void play(File path, int startPos) { this.startPos = startPos; play(path); } @Override public void play(Uri uri, int startPos) { this.startPos = startPos; play(uri); } @Override public void play(InputStream is, int startPos) { this.startPos = startPos; play(is); } @Override public void play(AssetFileDescriptor afd, int startPos) { this.startPos = startPos; play(afd, startPos); } private void play(AudioSource audioSource, int startPos, boolean play) { if(audioSource.is != null) { disableStartPlay = !play; this.startPos = startPos; play(audioSource.is, startPos); } else if(audioSource.afd != null) { disableStartPlay = !play; this.startPos = startPos; play(audioSource.afd, startPos); } else if(audioSource.uri != null) { disableStartPlay = !play; this.startPos = startPos; play(audioSource.uri, startPos); } else if(audioSource.filePath != null) { disableStartPlay = !play; this.startPos = startPos; play(audioSource.filePath, startPos); } } private void reset() { Log.i(LOGTAG, "MediaPlayer reset"); close(); mediaPlayer = new MediaPlayer(); mediaPlayer.setLooping(repeat); mediaPlayer.setOnErrorListener(this); mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnCompletionListener(this); } @Override public boolean getRepeat() { return repeat; } @Override public void setRepeat(boolean repeat) { this.repeat = repeat; if(mediaPlayer != null) { mediaPlayer.setLooping(repeat); } } @Override public void stop() { if(!preparing) { stopProgressNotifier(); mediaPlayer.stop(); paused = false; Log.i(LOGTAG, "Play stoped"); } } @Override public void pause() { if(!preparing) { stopProgressNotifier(); mediaPlayer.pause(); paused = true; Log.i(LOGTAG, "Play paused"); } } @Override public void resume() { if(!preparing && paused) { mediaPlayer.start(); startProgressNotifier(); paused = false; Log.i(LOGTAG, "Play resumed"); } } @Override public boolean isPlaying() { if(!preparing) { return mediaPlayer.isPlaying(); } return false; } @Override public void setVolume(float volume) { if(!preparing) { mediaPlayer.setVolume(volume, volume); } } @Override public void onCompletion(MediaPlayer mp) { if(mp.equals(mediaPlayer)) { stopProgressNotifier(); if(completeListener != null) { completeListener.complete(getClass()); } Log.i(LOGTAG, "Play completed"); } } @Override public void onPrepared(MediaPlayer mp) { if(mp.equals(mediaPlayer)) { Log.i(LOGTAG, "Audio prepared."); if(startPos != 0) { Log.i(LOGTAG, "Start seek play position:" + startPos); mediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mp) { Log.i(LOGTAG, "Play position set to:" + mediaPlayer.getCurrentPosition()); mediaPlayer.setOnSeekCompleteListener(null); onPrepared(); } }); mediaPlayer.seekTo(startPos); } else { onPrepared(); } } } private void onPrepared() { Log.i(LOGTAG, "Audio prepared. Start playing"); mediaPlayer.start(); if(disableStartPlay) { Log.i(LOGTAG, "Disable start play flag set"); mediaPlayer.pause(); disableStartPlay = false; paused = true; } else { startProgressNotifier(); } preparing = false; } private void startProgressNotifier() { if(progressListener != null) { if(handler == null) handler = new Handler(); progressNotifier = new ProgressNotifier(); handler.post(progressNotifier); } } private void stopProgressNotifier() { if(progressNotifier != null) progressNotifier.stop(); } @Override public int getDuration() { if(!preparing) { return mediaPlayer.getDuration(); } return 0; } @Override public int getPlayPosition() { if(!preparing) { return mediaPlayer.getCurrentPosition(); } return 0; } @Override public void setPlayPosition(int position) { if(!preparing) { mediaPlayer.seekTo(position); } } @Override public int getAudioStreamType() { return streamType; } @Override public void setAudioStreamType(int streamType) { this.streamType = streamType; if(!preparing) { Log.d(LOGTAG, "Set new audio stream type"); boolean play = mediaPlayer.isPlaying(); if(play || paused) { Log.d(LOGTAG, "Player is working. Restart player with the same position:" + getPlayPosition() + "; Play:" + play + ", Pause:" + paused); play(lastAudioSource, getPlayPosition(), play); } } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.e(LOGTAG, "Media preparation error:" + what + ", " + extra); return true; } @Override public OnCompleteListener<Class<?>> getOnCompleteListener() { return completeListener; } @Override public void setOnCompleteListener(OnCompleteListener<Class<?>> listener) { this.completeListener = listener; } @Override public OnProgressListener getOnProgressListener() { return progressListener; } @Override public void setOnProgressListener(OnProgressListener listener) { this.progressListener = listener; } @Override public void close() { preparing = true; stopProgressNotifier(); if(mediaPlayer != null) { if(isPlaying() || paused) stop(); mediaPlayer.release(); mediaPlayer = null; } } }