• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 
17 package com.google.android.mobly.snippet.bundled;
18 
19 import android.media.AudioAttributes;
20 import android.media.AudioManager;
21 import android.media.MediaPlayer;
22 import android.os.Build;
23 import android.os.Build.VERSION_CODES;
24 import com.google.android.mobly.snippet.Snippet;
25 import com.google.android.mobly.snippet.rpc.Rpc;
26 import java.io.IOException;
27 
28 /* Snippet class to control media playback. */
29 public class MediaSnippet implements Snippet {
30 
31     private final MediaPlayer mPlayer;
32 
MediaSnippet()33     public MediaSnippet() {
34         mPlayer = new MediaPlayer();
35     }
36 
37     @Rpc(description = "Resets snippet media player to an idle state, regardless of current state.")
mediaReset()38     public void mediaReset() {
39         mPlayer.reset();
40     }
41 
42     @Rpc(description = "Play an audio file stored at a specified file path in external storage.")
mediaPlayAudioFile(String mediaFilePath)43     public void mediaPlayAudioFile(String mediaFilePath) throws IOException {
44         mediaReset();
45         if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
46             mPlayer.setAudioAttributes(
47                     new AudioAttributes.Builder()
48                             .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
49                             .setUsage(AudioAttributes.USAGE_MEDIA)
50                             .build());
51         } else {
52             mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
53         }
54         mPlayer.setDataSource(mediaFilePath);
55         mPlayer.prepare(); // Synchronous call blocks until the player is ready for playback.
56         mPlayer.start();
57     }
58 
59     @Rpc(description = "Stops media playback.")
mediaStop()60     public void mediaStop() throws IOException {
61         mPlayer.stop();
62     }
63 
64     @Override
shutdown()65     public void shutdown() {}
66 }
67