1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.platform.helpers.media; 18 19 import android.media.MediaMetadata; 20 21 import androidx.annotation.Nullable; 22 23 import java.time.Duration; 24 import java.util.Timer; 25 import java.util.TimerTask; 26 27 final class MockMediaPlayer { 28 29 private final static int PERIOD = 1000; // milliseconds 30 31 private long mCurrentPosition; // current position in milliseconds. 32 private Timer mTimer; 33 @Nullable 34 private MediaMetadata mCurrentSource; 35 private Runnable mOnCompletionListener; 36 MockMediaPlayer()37 public MockMediaPlayer() { 38 mCurrentPosition = 0; 39 } 40 start()41 public void start() { 42 mTimer = new Timer(); 43 mTimer.scheduleAtFixedRate(new TimerTask() { 44 @Override 45 public void run() { 46 mCurrentPosition += PERIOD; 47 if (mCurrentPosition >= getDuration()) { 48 onCompletion(); 49 } 50 } 51 }, 0, PERIOD); 52 } 53 onCompletion()54 private void onCompletion() { 55 reset(); 56 if (mOnCompletionListener != null) { 57 mOnCompletionListener.run(); 58 } 59 } 60 setOnCompletionListener(@ullable Runnable listener)61 public void setOnCompletionListener(@Nullable Runnable listener) { 62 mOnCompletionListener = listener; 63 } 64 reset()65 public void reset() { 66 pause(); 67 mCurrentPosition = 0; 68 } 69 pause()70 public void pause() { 71 if (mTimer != null) { 72 mTimer.cancel(); 73 } 74 mTimer = null; 75 } 76 stop()77 public void stop() { 78 reset(); 79 } 80 getCurrentPosition()81 public long getCurrentPosition() { 82 return mCurrentPosition; 83 } 84 setDataSource(MediaMetadata source)85 public void setDataSource(MediaMetadata source) { 86 mCurrentSource = source; 87 } 88 getDuration()89 private long getDuration() { 90 return mCurrentSource.getLong(MediaMetadata.METADATA_KEY_DURATION); 91 } 92 } 93