1/*
2 * Copyright (C) 2017 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
17package com.googlecode.android_scripting.facade;
18
19import android.os.SystemClock;
20import android.speech.tts.TextToSpeech;
21import android.speech.tts.TextToSpeech.OnInitListener;
22
23import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
24import com.googlecode.android_scripting.rpc.Rpc;
25import com.googlecode.android_scripting.rpc.RpcParameter;
26
27import java.util.concurrent.CountDownLatch;
28
29/**
30 * Provides Text To Speech services
31 */
32
33public class TextToSpeechFacade extends RpcReceiver {
34
35  private final TextToSpeech mTts;
36  private final CountDownLatch mOnInitLock;
37
38  public TextToSpeechFacade(FacadeManager manager) {
39    super(manager);
40    mOnInitLock = new CountDownLatch(1);
41    mTts = new TextToSpeech(manager.getService(), new OnInitListener() {
42      @Override
43      public void onInit(int arg0) {
44        mOnInitLock.countDown();
45      }
46    });
47  }
48
49  @Override
50  public void shutdown() {
51    while (mTts.isSpeaking()) {
52      SystemClock.sleep(100);
53    }
54    mTts.shutdown();
55  }
56
57  @Rpc(description = "Speaks the provided message via TTS.")
58  public void ttsSpeak(@RpcParameter(name = "message") String message) throws InterruptedException {
59    mOnInitLock.await();
60    if (message != null) {
61      mTts.speak(message, TextToSpeech.QUEUE_ADD, null);
62    }
63  }
64
65  @Rpc(description = "Returns True if speech is currently in progress.")
66  public Boolean ttsIsSpeaking() throws InterruptedException {
67    mOnInitLock.await();
68    return mTts.isSpeaking();
69  }
70
71}
72