1 /* 2 * Copyright (C) 2015 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 com.android.cts.verifier.audio; 18 19 import android.media.AudioFormat; 20 import android.media.AudioManager; 21 import android.media.AudioTrack; 22 23 import java.lang.InterruptedException; 24 import java.lang.Math; 25 import java.lang.Runnable; 26 27 public class TrivialPlayer implements Runnable { 28 AudioTrack mAudioTrack; 29 int mBufferSize; 30 31 boolean mPlay; 32 boolean mIsPlaying; 33 34 short[] mAudioData; 35 36 Thread mFillerThread = null; 37 TrivialPlayer()38 public TrivialPlayer() { 39 mBufferSize = 40 AudioTrack.getMinBufferSize( 41 41000, 42 AudioFormat.CHANNEL_OUT_STEREO, 43 AudioFormat.ENCODING_PCM_16BIT); 44 mAudioTrack = 45 new AudioTrack( 46 AudioManager.STREAM_MUSIC, 47 41000, 48 AudioFormat.CHANNEL_OUT_STEREO, 49 AudioFormat.ENCODING_PCM_16BIT, 50 mBufferSize, 51 AudioTrack.MODE_STREAM); 52 53 mPlay = false; 54 mIsPlaying = false; 55 56 // setup audio data (silence will suffice) 57 mAudioData = new short[mBufferSize]; 58 for (int index = 0; index < mBufferSize; index++) { 59 // mAudioData[index] = 0; 60 // keep this code since one might want to hear the playnig audio 61 // for debugging/verification. 62 mAudioData[index] = 63 (short)(((Math.random() * 2.0) - 1.0) * (double)Short.MAX_VALUE/2.0); 64 } 65 } 66 getAudioTrack()67 public AudioTrack getAudioTrack() { return mAudioTrack; } 68 isPlaying()69 public boolean isPlaying() { 70 synchronized (this) { 71 return mIsPlaying; 72 } 73 } 74 start()75 public void start() { 76 mPlay = true; 77 mFillerThread = new Thread(this); 78 mFillerThread.start(); 79 } 80 stop()81 public void stop() { 82 mPlay = false; 83 mFillerThread = null; 84 } 85 shutDown()86 public void shutDown() { 87 stop(); 88 while (isPlaying()) { 89 try { 90 Thread.sleep(10); 91 } catch (InterruptedException ex) { 92 } 93 } 94 mAudioTrack.release(); 95 } 96 97 @Override run()98 public void run() { 99 mAudioTrack.play(); 100 synchronized (this) { 101 mIsPlaying = true; 102 } 103 while (mAudioTrack != null && mPlay) { 104 mAudioTrack.write(mAudioData, 0, mBufferSize); 105 } 106 synchronized (this) { 107 mIsPlaying = false; 108 } 109 mAudioTrack.stop(); 110 } 111 } 112