我有一个小应用程序,我希望能够将TTS音频发送到扬声器或蓝牙耳机(如果已连接)。它在扬声器电话模式下运行良好,但BT没有运气。知道如何解决这个问题吗?代码段如下:'
private void speak(String s){
HashMap<String, String> hash = new HashMap<String, String>();
hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_SYSTEM));
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.startBluetoothSco();
audioManager.setBluetoothScoOn(true);
tts.speak(s, TextToSpeech.QUEUE_ADD, hash);
}
答案 0 :(得分:3)
在Using the Android RecognizerIntent with a bluetooth headset
上使用我的回答在您声明私有的无效讲话(String s)的活动中,添加一个类成员
BluetoothHeadsetUtils mBluetoothHelper;
TelephonyManager mTelManager;
MyPhoneStateListener mPhoneStateListener = new MyPhoneStateListener();
在同一活动onCreate()上添加
@Override
public void onCreate()
{
mBluetoothHelper = new BluetoothHeadsetUtils(this);
mTelManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
onResume()和onPause的活动添加
@Override
onResume()
{
mBluetoothHelper.start();
}
@Override
onPause()
{
mBluetoothHelper.stop();
}
您可以将您的发言(字符串s)定义为
public void speak(String s, String utteranceId) // utteranceId can be an empty string
{
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
if (mBluetoothHelper.isOnHeadsetSco())
{
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_VOICE_CALL));
}
tts.speak(s, TextToSpeech.QUEUE_ADD, myHashRender);
}
而不是广播接收器使用电话状态监听器
protected class MyPhoneStateListener extends PhoneStateListener
{
@Override
public void onCallStateChanged(int state, String incomingNumber)
{
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
mAudioManager.setStreamMute(AudioManager.STREAM_RING, true);
speak("whatever you want here", "ringing"); //$NON-NLS-1$
Log.d(TAG, "ringing cancel recognizer"); //$NON-NLS-1$
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "offhook cancel recognizer"); //$NON-NLS-1$
break;
case TelephonyManager.CALL_STATE_IDLE:
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
}
mBluetoothHelper.start();
}
}).start();
Log.d(TAG, "call state idle"); //$NON-NLS-1$
}
}
}
在您的活动或服务中添加工具OnUtteranceCompletedListener并添加以下代码
@Override
public void onUtteranceCompleted(String utteranceId)
{
if (utteranceId.equals("ringing"))
{
mAudioManager.setStreamMute(AudioManager.STREAM_RING, false);
mBluetoothHelper.stop();
}
}