Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MediaPlayerWrapper
- {
- private static final String LOG_TAG = "MediaPlayerWrapper";
- private String mFilename;
- PlayerState mState = PlayerState.Stopped;
- MediaPlayer mPlayerEngine;
- int mStartTime;
- int mStopTime;
- int mVolume;
- Handler mHandler = new Handler();
- Runnable mStopPlayerTask = new Runnable(){
- @Override
- public void run() {
- stop(PlayStopReason.Finished);
- }};
- public MediaPlayerWrapper(Context context)
- {
- }
- public void play(AudioClip clip)
- throws IllegalStateException, IllegalArgumentException, SecurityException, IOException
- {
- Log.v(LOG_TAG, "play()");
- mPlayerEngine = new MediaPlayer();
- setAudioClip(clip);
- mPlayerEngine.start();
- mState = PlayerState.Playing;
- mHandler.postDelayed(mStopPlayerTask, clip.getStopTime()-clip.getStartTime());
- }
- public void stop(PlayStopReason reason)
- {
- Log.v(LOG_TAG, "stop()");
- if (PlayerState.Paused == mState || PlayerState.Playing == mState)
- {
- Log.d(LOG_TAG, "Stopping player...");
- mHandler.removeCallbacks(mStopPlayerTask);
- mPlayerEngine.stop();
- mState = PlayerState.Stopped;
- }
- }
- private void setAudioClip(AudioClip clip)
- throws IllegalStateException, IllegalArgumentException, SecurityException, IOException
- {
- Log.v(LOG_TAG, "setAudioClip()");
- mFilename = clip.getSource();
- if (null == mFilename || mFilename.equals(""))
- {
- String text = "The given audio file name is empty!";
- Log.e(LOG_TAG, text);
- throw new IllegalStateException(text);
- }
- File f = new File(mFilename);
- if (!f.exists())
- {
- String text = "The specified file [" + mFilename + "] does not exist!";
- Log.e(LOG_TAG, "text");
- throw new FileNotFoundException(text);
- }
- try
- {
- mPlayerEngine.setDataSource(mFilename);
- mPlayerEngine.prepare();
- }catch(Exception ex)
- {
- Log.e(LOG_TAG, "An error happened preparing media player: " + ex.getMessage());
- ex.printStackTrace();
- }
- mStartTime = clip.getStartTime();
- mStopTime = clip.getStopTime();
- setPosition(mStartTime);
- }
- public void pause()
- {
- if (PlayerState.Playing == mState)
- {
- mPlayerEngine.pause();
- mHandler.removeCallbacks(mStopPlayerTask);
- mState = PlayerState.Paused;
- }
- }
- public void resume()
- {
- if (PlayerState.Paused == mState)
- {
- mHandler.postDelayed(mStopPlayerTask, mStopTime-mPlayerEngine.getCurrentPosition());
- mPlayerEngine.start();
- mState = PlayerState.Playing;
- }
- }
- private void setPosition(int pos)
- {
- Log.v(LOG_TAG, "setPosition()");
- mPlayerEngine.seekTo(pos);
- }
- @Override
- public void playRequested(AudioClip clip)
- {
- try
- {
- play(clip);
- } catch (Exception e)
- {
- //TODO: Inform user that the book is corrupted.
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement