Home | History | Annotate | Download | only in mediapicker
      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 package com.android.messaging.ui.mediapicker;
     17 
     18 import com.google.common.base.Preconditions;
     19 
     20 import javax.annotation.concurrent.ThreadSafe;
     21 
     22 /**
     23  * Keeps track of the speech level as last observed by the recognition
     24  * engine as microphone data flows through it. Can be polled by the UI to
     25  * animate its views.
     26  */
     27 @ThreadSafe
     28 public class AudioLevelSource {
     29     private volatile int mSpeechLevel;
     30     private volatile Listener mListener;
     31 
     32     public static final int LEVEL_UNKNOWN = -1;
     33 
     34     public interface Listener {
     35         void onSpeechLevel(int speechLevel);
     36     }
     37 
     38     public void setSpeechLevel(int speechLevel) {
     39         Preconditions.checkArgument(speechLevel >= 0 && speechLevel <= 100 ||
     40                 speechLevel == LEVEL_UNKNOWN);
     41         mSpeechLevel = speechLevel;
     42         maybeNotify();
     43     }
     44 
     45     public int getSpeechLevel() {
     46         return mSpeechLevel;
     47     }
     48 
     49     public void reset() {
     50         setSpeechLevel(LEVEL_UNKNOWN);
     51     }
     52 
     53     public boolean isValid() {
     54         return mSpeechLevel > 0;
     55     }
     56 
     57     private void maybeNotify() {
     58         final Listener l = mListener;
     59         if (l != null) {
     60             l.onSpeechLevel(mSpeechLevel);
     61         }
     62     }
     63 
     64     public synchronized void setListener(Listener listener) {
     65         mListener = listener;
     66     }
     67 
     68     public synchronized void clearListener(Listener listener) {
     69         if (mListener == listener) {
     70             mListener = null;
     71         }
     72     }
     73 }
     74