Here are the examples of the java api android.bluetooth.BluetoothA2dp taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
8 Examples
19
Source : VoiceMediator.java
with Apache License 2.0
from LingjuAI
with Apache License 2.0
from LingjuAI
public void setBluetoothA2dp(BluetoothA2dp bluetoothA2dp) {
this.bluetoothA2dp = bluetoothA2dp;
}
17
Source : BluetoothA2dpSnippet.java
with Apache License 2.0
from google
with Apache License 2.0
from google
public clreplaced BluetoothA2dpSnippet implements Snippet {
private static clreplaced BluetoothA2dpSnippetException extends Exception {
private static final long serialVersionUID = 1;
BluetoothA2dpSnippetException(String msg) {
super(msg);
}
}
private Context mContext;
private static boolean sIsA2dpProfileReady = false;
private static BluetoothA2dp sA2dpProfile;
private final JsonSerializer mJsonSerializer = new JsonSerializer();
public BluetoothA2dpSnippet() {
mContext = InstrumentationRegistry.getInstrumentation().getContext();
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.getProfileProxy(mContext, new A2dpServiceListener(), BluetoothProfile.A2DP);
Utils.waitUntil(() -> sIsA2dpProfileReady, 60);
}
private static clreplaced A2dpServiceListener implements BluetoothProfile.ServiceListener {
public void onServiceConnected(int var1, BluetoothProfile profile) {
sA2dpProfile = (BluetoothA2dp) profile;
sIsA2dpProfileReady = true;
}
public void onServiceDisconnected(int var1) {
sIsA2dpProfileReady = false;
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@RpcMinSdk(Build.VERSION_CODES.KITKAT)
@Rpc(description = "Connects to a paired or discovered device with A2DP profile." + "If a device has been discovered but not paired, this will pair it.")
public void btA2dpConnect(String deviceAddress) throws Throwable {
BluetoothDevice device = BluetoothAdapterSnippet.getKnownDeviceByAddress(deviceAddress);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
mContext.registerReceiver(new PairingBroadcastReceiver(mContext), filter);
Utils.invokeByReflection(sA2dpProfile, "connect", device);
if (!Utils.waitUntil(() -> sA2dpProfile.getConnectionState(device) == BluetoothA2dp.STATE_CONNECTED, 120)) {
throw new BluetoothA2dpSnippetException("Failed to connect to device " + device.getName() + "|" + device.getAddress() + " with A2DP profile within 2min.");
}
}
@Rpc(description = "Disconnects a device from A2DP profile.")
public void btA2dpDisconnect(String deviceAddress) throws Throwable {
BluetoothDevice device = getConnectedBluetoothDevice(deviceAddress);
Utils.invokeByReflection(sA2dpProfile, "disconnect", device);
if (!Utils.waitUntil(() -> sA2dpProfile.getConnectionState(device) == BluetoothA2dp.STATE_DISCONNECTED, 120)) {
throw new BluetoothA2dpSnippetException("Failed to disconnect device " + device.getName() + "|" + device.getAddress() + " from A2DP profile within 2min.");
}
}
@Rpc(description = "Gets all the devices currently connected via A2DP profile.")
public ArrayList<Bundle> btA2dpGetConnectedDevices() {
return mJsonSerializer.serializeBluetoothDeviceList(sA2dpProfile.getConnectedDevices());
}
@Rpc(description = "Checks if a device is streaming audio via A2DP profile.")
public boolean btIsA2dpPlaying(String deviceAddress) throws Throwable {
BluetoothDevice device = getConnectedBluetoothDevice(deviceAddress);
return sA2dpProfile.isA2dpPlaying(device);
}
private BluetoothDevice getConnectedBluetoothDevice(String deviceAddress) throws BluetoothA2dpSnippetException {
for (BluetoothDevice device : sA2dpProfile.getConnectedDevices()) {
if (device.getAddress().equalsIgnoreCase(deviceAddress)) {
return device;
}
}
throw new BluetoothA2dpSnippetException("No device with address " + deviceAddress + " is connected via A2DP.");
}
@Override
public void shutdown() {
}
}
17
Source : BluetoothProfileServiceTemplate.java
with Apache License 2.0
from devyok
with Apache License 2.0
from devyok
protected boolean setPriority2(int priority, BluetoothDevice device, BluetoothProfile profile) {
if (this.profileType == BluetoothProfile.A2DP) {
BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) profile;
return bluetoothA2dp.setPriority(device, priority);
} else if (this.profileType == BluetoothProfile.HEADSET) {
BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) profile;
return bluetoothHeadset.setPriority(device, priority);
}
return false;
}
16
Source : BluetoothProfileServiceTemplate.java
with Apache License 2.0
from devyok
with Apache License 2.0
from devyok
protected boolean connect2(BluetoothDevice device, BluetoothProfile profile) {
if (this.profileType == BluetoothProfile.A2DP) {
BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) profile;
return bluetoothA2dp.connect(device);
} else if (this.profileType == BluetoothProfile.HEADSET) {
BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) profile;
return bluetoothHeadset.connect(device);
}
return false;
}
16
Source : BluetoothProfileServiceTemplate.java
with Apache License 2.0
from devyok
with Apache License 2.0
from devyok
protected int getPriority2(BluetoothDevice device, BluetoothProfile profile) {
if (this.profileType == BluetoothProfile.A2DP) {
BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) profile;
return bluetoothA2dp.getPriority(device);
} else if (this.profileType == BluetoothProfile.HEADSET) {
BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) profile;
return bluetoothHeadset.getPriority(device);
}
return -1;
}
15
Source : BluetoothProfileServiceTemplate.java
with Apache License 2.0
from devyok
with Apache License 2.0
from devyok
protected boolean disconnect2(BluetoothDevice device, BluetoothProfile profile) {
if (this.profileType == BluetoothProfile.A2DP) {
BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) profile;
return bluetoothA2dp.disconnect(device);
} else if (this.profileType == BluetoothProfile.HEADSET) {
BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) profile;
return bluetoothHeadset.disconnect(device);
}
return false;
}
12
Source : VoiceMediator.java
with Apache License 2.0
from LingjuAI
with Apache License 2.0
from LingjuAI
/**
* Created by Administrator on 2016/11/5.
*/
public clreplaced VoiceMediator implements SystemVoiceMediator {
private final static String TAG = "VoiceMediator";
public final static int AUTO_TYPE = 0;
public final static int XIMALAYA_TYPE = 1;
private static VoiceMediator instance;
// 识别引擎
protected RecognizerBase recognizer;
// 合成引擎
protected SynthesizerBase synthesizer;
// 唤醒引擎
protected WakeupEngineBase awakener;
private ChatStateListener chatListener;
private Context mContext;
private boolean isHeadSet;
private BluetoothA2dp bluetoothA2dp;
private BluetoothHeadset bluetoothHeadset;
private boolean isBlueHeadSet;
private boolean suportA2DP;
private int remindDialogFlag;
// 记录最新一次对话处于什么动作场景,用于判断不说话时是否推送NOANSWER
private CmdAction currentAction;
/**
* 是否处于唤醒录音模式状态标记
*/
private boolean is_wakeup_mode = false;
/**
* 音频播放类型(0:歌曲 1:有声内容)
*/
private int audioPlayType = AUTO_TYPE;
/**
* 是否正在通话中
*/
private boolean mobileRing = false;
/**
* 是否处于来电响铃中
*/
private boolean calling = false;
// 当前媒体音量
private int mCurrentVolume;
private AudioManager mAudioManager;
private AtomicBoolean robotResponse = new AtomicBoolean(false);
protected SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
protected int waitID;
protected int waitPlayID;
private boolean is_walk_navi;
protected VoiceMediator(Context context) {
this.mContext = context;
initVoiceComponent();
try {
waitID = soundPool.load(mContext.getreplacedets().openFd(mContext.getResources().getString(R.string.audio_wait_response)), 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
EventBus.getDefault().register(this);
}
}
public static synchronized VoiceMediator create(Context context) {
if (instance == null)
instance = new VoiceMediator(context);
return instance;
}
public static VoiceMediator get() {
return instance;
}
protected void initVoiceComponent() {
Log.i(TAG, "initVoiceComponent>>>>>>>>>>>>>>>>>>>>>>>>>>>");
/*tPools.execute(new Runnable() {
@Override
public void run() {
for(String s:BaiduSynthesizer.OFFLINE_RS){
copyFromreplacedetsToSdcard(RobotApplication.firstOpen,s,Setting.DEFAULT_DIR+"/"+s);
}
synthesizer = BaiduSynthesizer.createInstance(RobotService.this);
}
});*/
// recognizer= BaiduRecognizer.createInstance(RobotService.this);
SpeechUtility.createUtility(mContext, SpeechConstant.APPID + "=" + Constants.XUNFEI_APPID + "," + SpeechConstant.MODE_MSC + "=" + SpeechConstant.MODE_AUTO);
// com.iflytek.cloud.Setting.setLogLevel(Setting.LOG_LEVEL.detail);
com.iflytek.cloud.Setting.setShowLog(false);
com.iflytek.cloud.Setting.setLocationEnable(true);
Single.just(0).doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Exception {
recognizer = IflyRecognizer.createInstance(mContext, VoiceMediator.this);
synthesizer = IflySynthesizer.createInstance(mContext, VoiceMediator.this);
awakener = VoiceAwakener.createInstance(mContext, VoiceMediator.this);
}
}).subscribeOn(Schedulers.newThread()).subscribe();
Log.i(TAG, "initVoiceComponent>>>>>>>>>>>>>>>>>>>>>>>>>>>END");
}
/**
* 耳机操作事件处理
*/
@Subscribe
public void onHeadSetEvent(HeadSetEvent e) {
switch(e) {
case Connect:
this.isHeadSet = true;
getHook();
EventBus.getDefault().post(new ChatMsgEvent(new ResponseMsg(mContext.getResources().getString(R.string.headset_mode_tips)), null, null, null));
break;
case Disconnect:
this.isHeadSet = false;
if (mAudioManager != null)
mAudioManager.abandonAudioFocus(mFocusChangeListener);
break;
case Click:
break;
case DoubleClick:
break;
case TrebleClick:
break;
}
}
/**
* 获取音频焦点,夺回耳机按键广播
*/
public void getHook() {
if (AppConfig.dPreferences.getBoolean(AppConfig.ALLOW_WIRE, true)) {
if (mAudioManager == null)
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
// 抢回焦点
/**
* 由于耳机广播注册对象是单例且广播接受者唯一的,如果接收者栈中已存在该接收者对象则直接返回。
* 所以在重新注册本应用的耳机广播接收者之前需要先注销已失效但仍存在的接收者 *
*/
mAudioManager.unregisterMediaButtonEventReceiver(new ComponentName(mContext.getApplicationContext(), MediaButtonReceiver.clreplaced));
isFocus = mAudioManager.requestAudioFocus(mFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_FAILED;
/* 注册耳机广播接收者 */
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(mContext.getApplicationContext(), MediaButtonReceiver.clreplaced));
Log.i("LingJu", "MainActivity getHook():" + mAudioManager.isMusicActive());
}
}
public boolean isFocus() {
return isFocus;
}
/**
* 是否获取到音频焦点标记
*/
private boolean isFocus = true;
private AudioManager.OnAudioFocusChangeListener mFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
Log.i("LingJu", "焦点状态:" + focusChange);
switch(focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
isFocus = false;
mAudioManager.abandonAudioFocus(mFocusChangeListener);
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.i("LingJu", "MainActivity onAudioFocusChange()");
isFocus = true;
break;
}
}
};
public void setBluetoothHeadset(BluetoothHeadset bluetoothHeadset) {
this.bluetoothHeadset = bluetoothHeadset;
}
public void setBluetoothA2dp(BluetoothA2dp bluetoothA2dp) {
this.bluetoothA2dp = bluetoothA2dp;
}
@Override
public BluetoothHeadset getBluetoothHeadset() {
return bluetoothHeadset;
}
@Override
public BluetoothA2dp getBluetoothA2dp() {
return bluetoothA2dp;
}
public void setBlueHeadSet(boolean blueHeadSet) {
isBlueHeadSet = blueHeadSet;
}
public void setSuportA2DP(boolean suportA2DP) {
this.suportA2DP = suportA2DP;
}
/**
* 设置合成参数
*/
public void setSynthParams(NetUtil.NetType type) {
synthesizer.resetParam(type);
}
@Override
public boolean isPlaying() {
return LingjuAudioPlayer.get().isPlaying();
}
@Override
public boolean isTinging() {
return XmPlayerManager.getInstance(mContext).isPlaying();
}
@Override
public void setAudioPlayType(int playType) {
this.audioPlayType = playType;
}
@Override
public int getAudioPlayType() {
return audioPlayType;
}
@Override
public boolean isHeadset() {
return isHeadSet;
}
public void setHeadSet(boolean isHeadSet) {
this.isHeadSet = isHeadSet;
}
@Override
public boolean isWakeUpMode() {
return is_wakeup_mode;
}
@Override
public void setWakeupModeFlag(boolean isWakeUpMode) {
is_wakeup_mode = isWakeUpMode;
}
@Override
public boolean isBlueToothHeadSet() {
return isBlueHeadSet;
}
public boolean isSuportA2DP() {
return suportA2DP;
}
@Override
public void openBlueHeadSet4Recognition() {
if (isBlueToothHeadSet() && getBluetoothHeadset() != null && !getBluetoothHeadset().getConnectedDevices().isEmpty()) {
int c = 0;
BluetoothDevice device = getBluetoothHeadset().getConnectedDevices().get(0);
while (isBlueToothHeadSet() && !getBluetoothHeadset().isAudioConnected(device)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "c=" + c);
c++;
if (c > 30) {
break;
}
}
}
}
@Override
public void startBluetoothSco() {
if (isBlueToothHeadSet()) {
BluetoothHeadset headset = getBluetoothHeadset();
if (headset == null || headset.getConnectedDevices().isEmpty() || headset.isAudioConnected(headset.getConnectedDevices().get(0)))
return;
Log.e(TAG, "startBluetoothSco:device size=" + headset.getConnectedDevices().size());
headset.startVoiceRecognition(headset.getConnectedDevices().get(0));
}
}
@Override
public void stopBluetoothSco() {
if (isBlueToothHeadSet() && getBluetoothHeadset() != null && !getBluetoothHeadset().getConnectedDevices().isEmpty()) {
if (getBluetoothHeadset().isAudioConnected(getBluetoothHeadset().getConnectedDevices().get(0))) {
Log.e(TAG, "stopBluetoothSco>>stopBluetoothSco");
getBluetoothHeadset().stopVoiceRecognition(getBluetoothHeadset().getConnectedDevices().get(0));
try {
int c = 0;
while (getBluetoothHeadset().isAudioConnected(getBluetoothHeadset().getConnectedDevices().get(0))) {
Thread.sleep(100);
Log.e(TAG, "stopBluetoothSco c=" + c);
c++;
if (c > 10) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
public void stopSynthesize() {
if (synthesizer != null) {
Log.i(TAG, "stopsynthe................");
synthesizer.stopSpeakingAbsolte();
}
}
/**
* 停止识别和说话并且尝试打开唤醒(如果当前为唤醒模式则可以打开)
*/
public void stopSpeakAndWakeup(boolean wakeup) {
stopRecognize();
synthesizer.stopSpeakingAbsolte();
if (wakeup)
tryToWakeup();
}
/**
* 尝试打开唤醒(如果当前为唤醒模式则可以打开)
*/
@Override
public void tryToWakeup() {
Log.i("LingJu", "VoiceMediator tryToWakeup()>>> " + is_wakeup_mode);
if (is_wakeup_mode)
startWakeup();
}
@Override
public void changeMediaVolume(int percent) {
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int volume = (int) ((percent / 100.0) * maxVolume + 0.5);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
}
@Override
public void recordCurrentVolume() {
is_walk_navi = true;
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
@Override
public void resumeMediaVolume() {
is_walk_navi = false;
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mCurrentVolume, 0);
}
@Override
public boolean isWalkNavi() {
return is_walk_navi;
}
@Override
public void stopRecognize() {
Log.i(TAG, "stopRecognize");
if (recognizer != null) {
recognizer.stopRecognize();
}
}
@Override
public void onWakenup(String wakeupWord) {
/* 唤醒成功,开启识别 */
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORDING));
startRecognize();
}
@Override
public void sendMsg2Robot(String msg) {
if (chatListener != null)
chatListener.onInput(msg);
}
@Override
public void setWakeUpMode(boolean flag) {
if (synthesizer != null) {
is_wakeup_mode = flag;
AppConfig.dPreferences.edit().putBoolean(AppConfig.WAKEUP_MODE, flag).commit();
if (flag) {
if (synthesizer.isSpeaking() || recognizer.isRecognizing()) {
return;
} else {
startWakeup();
}
} else {
stopWakenup();
}
}
}
@Override
public boolean allowSynthersize(SpeechMsg msg) {
boolean result = true;
try {
if (BNavigatorProxy.getInstance().isNaviBegin() && msg.origin() == SpeechMsg.ORIGIN_DEFAULT) {
msg.getBuilder().setOrigin(SpeechMsg.ORIGIN_COMMON);
}
/*if (!isHeadSet) { //合成声音先关闭唤醒
stopWakenup();
}*/
if (msg.priority() == SpeechMsg.PRIORITY_ABOVE_RECOGNIZE) {
// 合成优先
Intent intent = new Intent(mContext, replacedistantService.clreplaced);
intent.putExtra(replacedistantService.CMD, replacedistantService.ServiceCmd.STOP_RECOGNIZE);
mContext.startService(intent);
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORD_IDLE));
} else {
if (recognizer.isRecognizing()) {
// 识别优先
result = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "allowSynthersize>>" + Boolean.toString(result));
return result;
}
@Override
public boolean compareSpeechMsg(SpeechMsg nSpeechMsg, SpeechMsg currentSpeechMsg) {
if (currentSpeechMsg != null && currentSpeechMsg.origin() == SpeechMsg.ORIGIN_NAVI) {
if (nSpeechMsg.origin() != SpeechMsg.ORIGIN_NAVI) {
if (nSpeechMsg.origin() == SpeechMsg.ORIGIN_DEFAULT)
nSpeechMsg.getBuilder().setOrigin(SpeechMsg.ORIGIN_COMMON);
return false;
}
}
return true;
}
public void setCurrentAction(CmdAction action) {
this.currentAction = action;
}
@Override
public void onRecognizeError(int code, String msg) {
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORD_IDLE_AFTER_RECOGNIZED));
if (recognizer.isPlayingBeforRecognize()) {
EventBus.getDefault().post(LingjuAudioPlayer.get().currentPlayMusic());
LingjuAudioPlayer.get().play();
}
if (recognizer.isTingBeforeRecognize()) {
XmPlayerManager.getInstance(mContext).play();
}
tryToWakeup();
boolean showError = false;
switch(code) {
// 10114
case ErrorCode.MSP_ERROR_TIME_OUT:
// 20002
case ErrorCode.ERROR_NETWORK_TIMEOUT:
// 20003
case ErrorCode.ERROR_NET_EXCEPTION:
case // 20001
ErrorCode.ERROR_NO_NETWORK:
msg = Setting.RECOGNIZE_NETWORK_ERROR;
break;
case 20005:
msg = Setting.RECOGNIZE_NOMATCH_ERROR;
break;
case // 10118
ErrorCode.MSP_ERROR_NO_DATA:
// TODO: 2017/5/18 等待拨号、发短信时不做任何回复
if ((currentAction == null || ((currentAction.getOutc() & DefaultProcessor.OUTC_ASK) != DefaultProcessor.OUTC_ASK)) && !EventBus.getDefault().hreplacedubscriberForEvent(NavigateEvent.clreplaced)) {
msg = Setting.RECOGNIZE_NODATA_ERROR;
} else {
Intent intent = new Intent(mContext, replacedistantService.clreplaced);
intent.putExtra(replacedistantService.CMD, replacedistantService.ServiceCmd.SEND_TO_ROBOT);
intent.putExtra(replacedistantService.TEXT, ChatRobotBuilder.NOANSWER);
mContext.startService(intent);
return;
}
break;
case 20017:
msg = "很抱歉,识别引擎出错,请关闭程序重试!";
showError = true;
break;
case ErrorCode.ERROR_AUDIO_RECORD:
msg = msg + ",请您在设置-应用管理-应用详情下的权限管理检查是否允许录音权限";
showError = true;
break;
default:
msg = Setting.RECOGNIZE_ERROR_TIPS;
break;
}
if (showError) {
EventBus.getDefault().post(new SynthesizeEvent());
}
if (!TextUtils.isEmpty(msg)) /* && code == ErrorCode.MSP_ERROR_NO_DATA*/
{
EventBus.getDefault().post(new ChatMsgEvent(new ResponseMsg(msg), null, null, null));
speak(new SpeechMsgBuilder(msg), true);
}
}
private void speak(SpeechMsgBuilder msgBuilder, final boolean isAnim) {
SynthesizerBase.get().startSpeakAbsolute(msgBuilder.build()).doOnNext(new Consumer<SpeechMsg>() {
@Override
public void accept(SpeechMsg speechMsg) throws Exception {
if (speechMsg.state() == SpeechMsg.State.OnBegin && isAnim)
EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_START));
}
}).doOnComplete(new Action() {
@Override
public void run() throws Exception {
EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_END));
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.computation()).subscribe();
}
@Override
public void onRecoginzeWait() {
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECOGNIZING));
}
@Override
public void onRecoginzeResult(String result) {
Log.i(TAG, "onRecoginzeResult>>" + result);
if (EventBus.getDefault().hreplacedubscriberForEvent(NavigateEvent.clreplaced)) {
EventBus.getDefault().post(new NavigateEvent(NavigateEvent.STOP_COUNTDOWN));
}
if (recognizer.isPlayingBeforRecognize()) {
PlayMusic music = LingjuAudioPlayer.get().currentPlayMusic();
if (music != null)
EventBus.getDefault().post(music);
LingjuAudioPlayer.get().play();
}
if (recognizer.isTingBeforeRecognize()) {
XmPlayerManager.getInstance(mContext).play();
}
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORD_IDLE_AFTER_RECOGNIZED));
if (!TextUtils.isEmpty(result) && !"。".equals(result)) {
// 将识别结果发送给机器人
if (chatListener != null) {
robotResponse.set(false);
Observable.just(0).delay(750, TimeUnit.MILLISECONDS).filter(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Exception {
Log.i("LingJu", "过滤器:" + (!robotResponse.get()));
return !robotResponse.get();
}
}).doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
if (!robotResponse.get()) {
Log.i("LingJu", "播放等待提示音");
AudioManager mgr = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
waitPlayID = soundPool.play(waitID, volume, volume, 1, -1, 1f);
}
}
}).observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe();
chatListener.onInput(result);
/* 添加模式不需要将识别文本添加聊天视图 */
if (result.contains("&"))
result = result.substring(0, result.lastIndexOf("&"));
EventBus.getDefault().post(new ChatMsgEvent(new com.lingju.model.temp.speech.SpeechMsg(result), null, null, null));
}
} else {
onRecognizeError(ErrorCode.MSP_ERROR_NO_DATA, "");
}
}
/**
* 结束录音模式时调用
*/
@Override
public void onTapeResult(final String tapeContent) {
if (TextUtils.isEmpty(tapeContent)) {
currentAction.setOutc(1);
onRecognizeError(ErrorCode.MSP_ERROR_NO_DATA, Setting.RECOGNIZE_NODATA_ERROR);
return;
}
// 退出录音模式
IflyRecognizer.getInstance().setRecognizeMode(false);
String tapePath = PcmRecorder.TAPE_SRC + System.currentTimeMillis() + ".amr";
// 压缩并保存录音文件
AmrEncoder.pcm2Amr(PcmRecorder.TEMP_FILE, tapePath);
final Tape tape = new Tape();
tape.setText(tapeContent);
tape.setUrl(tapePath);
tape.setCreated(new Date());
tape.setSynced(false);
// 保存录音记录
TapeEnreplacedyDao.getInstance().insertTape(tape);
// 上传录音对象方式1(新策略,暂未实现)
// uploadTapeEnreplacedy(tape);
// Log.i("LingJu", "onSyncComplete()>>>" + tape.getSid());
TapeEnreplacedyDao.getInstance().setOnSyncListener(new TapeEnreplacedyDao.OnSyncListener() {
@Override
public void onSyncComplete() {
Log.i("LingJu", "onSyncComplete()>>>" + tape.getSid());
onRecoginzeResult(tapeContent + "&" + tape.getSid());
}
});
// //上传录音对象方式2(同步记录)
TapeEnreplacedyDao.getInstance().sync();
}
private void uploadTapeEnreplacedy(Tape tape) {
TapeEnreplacedy enreplacedy = new TapeEnreplacedy();
enreplacedy.setText(tape.getText());
enreplacedy.setUrl(tape.getUrl());
enreplacedy.setCreated(tape.getCreated());
enreplacedy.setModified(tape.getModified());
enreplacedy.setLid(tape.getId().intValue());
enreplacedy.setSid(tape.getSid());
enreplacedy.setRecyle(tape.getRecyle());
enreplacedy.setSynced(tape.getSynced());
enreplacedy.setTimestamp(tape.getTimestamp());
AndroidChatRobotBuilder.get().robot().append(enreplacedy);
}
@Override
public void stopWaitPlay() {
soundPool.stop(waitPlayID);
}
@Override
public void setRobotResponse(boolean hasResponse) {
robotResponse.set(hasResponse);
}
/**
* 长时间录音识别结果回调,该模式下不需要将识别文本作为对话输出
*/
@Override
public void onLongRecoginzeResult(String result) {
EventBus.getDefault().post(new LongRecognizeEvent(result));
}
@Override
public void startRecognize() {
Log.i(TAG, "startRecognize");
if (synthesizer.isSpeaking()) {
synthesizer.stopSpeakingAbsolte();
}
recognizer.startRecognize();
}
/**
* 提醒提前天数弹窗设置标记
*/
public void setRemindDialogFlag(int flag) {
// 0代表默认、1代表提醒天数弹窗
remindDialogFlag = flag;
}
/**
* 根据msg设置的模式进行对应的语音操作
*/
@Override
public void keepVoiceCtrl(SpeechMsg msg) {
switch(msg.contextMode()) {
case SpeechMsg.CONTEXT_KEEP_RECOGNIZE:
if (msg.state() == SpeechMsg.State.Completed) {
startRecognize();
// remindDialogFlag为0代表默认、1代表提醒天数弹窗
EventBus.getDefault().post(new RecordUpdateEvent(RecordUpdateEvent.RECORDING, remindDialogFlag));
}
break;
case SpeechMsg.CONTEXT_KEEP_AWAKEN:
tryToWakeup();
break;
default:
break;
}
}
@Override
public void setCalling(boolean isCalling) {
this.calling = isCalling;
}
@Override
public boolean isCalling() {
return calling;
}
@Override
public void setMobileRing(boolean mobileRing) {
this.mobileRing = mobileRing;
}
@Override
public boolean mobileRing() {
return mobileRing;
}
@Override
public void pausePlay() {
LingjuAudioPlayer.get().pause();
}
@Override
public void pauseTing() {
XmPlayerManager.getInstance(mContext).pause();
}
@Override
public void startWakeup() {
if (awakener != null) {
awakener.startListening();
}
}
/**
* 关闭唤醒
*/
@Override
public void stopWakenup() {
if (awakener != null)
awakener.stopCompletely();
}
@Override
public void updateLexicon() {
String[] keywords = mContext.getResources().getStringArray(R.array.keywords);
UserWords userWords = new UserWords();
for (String keyword : keywords) {
userWords.putWord(keyword);
}
recognizer.updateLexicon(userWords.toString());
}
@Override
public void onRecoginzeBegin() {
Log.i(TAG, "onRecoginzeBegin");
stopWaitPlay();
}
@Override
public void onRecoginzeVolumeChanged(int v) {
EventBus.getDefault().post(new VolumeChangedEvent(v));
}
@Override
public boolean preToCall() {
return false;
}
@Override
public void onSynthesizerInited(int code) {
}
@Override
public void onSynthesizerError(String errorMsg) {
EventBus.getDefault().post(new ChatMsgEvent(new ResponseMsg(errorMsg), null, null, null));
}
// 打开扬声器
@Override
public boolean openSpeaker() {
Log.e(TAG, "openSpeaker");
if (isHeadSet)
return false;
try {
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
switch(mAudioManager.getMode()) {
case AudioManager.MODE_IN_CALL:
System.out.println("MODE_IN_CALL");
break;
case AudioManager.MODE_IN_COMMUNICATION:
System.out.println("MODE_IN_COMMUNICATION");
break;
case AudioManager.MODE_NORMAL:
System.out.println("MODE_NORMAL");
break;
case AudioManager.MODE_RINGTONE:
System.out.println("MODE_RINGTONE");
break;
case AudioManager.MODE_INVALID:
System.out.println("MODE_INVALID");
break;
}
if (!mAudioManager.isSpeakerphoneOn() && mAudioManager.getMode() == AudioManager.MODE_IN_CALL) {
Log.e(TAG, "openSpeaker>>setSpeakerphoneOn");
mAudioManager.setSpeakerphoneOn(true);
mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.STREAM_VOICE_CALL);
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public Handler createHandler() {
return new Handler(Looper.getMainLooper());
}
public void setChatStateListener(ChatStateListener chatListener) {
this.chatListener = chatListener;
}
}
7
Source : MainActivity.java
with Apache License 2.0
from LiuJunb
with Apache License 2.0
from LiuJunb
public clreplaced MainActivity extends BaseActivity implements View.OnClickListener {
private static final int ENABLE_BLUE = 100;
private static final String MAINACTIVITY = "MainActivity";
/**
* 自定义返回码
*/
private static final int MY_PERMISSION_REQUEST_CONSTANT = 123456;
@Bind(R.id.btn_start)
Button btnStart;
@Bind(R.id.btn_public)
Button btnPublic;
@Bind(R.id.btn_search)
Button btnSearch;
@Bind(R.id.ls_blue)
ListView lsBlue;
@Bind(R.id.btn_stop)
Button btnStop;
@Bind(R.id.btn_play)
Button btnPlay;
@Bind(R.id.btn_stop_play)
Button btnStopPlay;
private BluetoothAdapter mBluetoothAdapter;
private Set<BluetoothDevice> devices;
private Set<BlueDevice> setDevices = new HashSet<>();
private BlueAdapter blueAdapter;
private IntentFilter mFilter;
/**
* 蓝牙音频传输协议
*/
private BluetoothA2dp a2dp;
/**
* 需要连接的蓝牙设备
*/
private BluetoothDevice currentBluetoothDevice;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
/**
* 判断手机系统的版本
*/
Log.d("MainActivity", Build.VERSION.SDK_INT + "");
if (Build.VERSION.SDK_INT >= 6.0) {
// Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
/**
* 动态添加权限:ACCESS_FINE_LOCATION
*/
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSION_REQUEST_CONSTANT);
}
}
initDate();
setListener();
}
/**
* 请求权限的回调:这里判断权限是否添加成功
*/
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch(requestCode) {
case MY_PERMISSION_REQUEST_CONSTANT:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("main", "添加权限成功");
}
return;
}
}
}
private void initDate() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/**
* 注册搜索蓝牙receiver
*/
mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mFilter.addAction(BluetoothDevice.ACTION_FOUND);
mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mReceiver, mFilter);
/**
* 注册配对状态改变监听器
*/
// IntentFilter mFilter = new IntentFilter();
// mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
// mFilter.addAction(BluetoothDevice.ACTION_FOUND);
// registerReceiver(mReceiver, mFilter);
getBondedDevices();
}
private void setListener() {
btnStart.setOnClickListener(this);
btnPublic.setOnClickListener(this);
btnSearch.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnPlay.setOnClickListener(this);
btnStopPlay.setOnClickListener(this);
lsBlue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
List<BlueDevice> listDevices = blueAdapter.getListDevices();
final BlueDevice blueDevice = listDevices.get(i);
String msg = "";
/**
* 还没有配对
*/
if (blueDevice.getDevice().getBondState() != BluetoothDevice.BOND_BONDED) {
msg = "是否与设备" + blueDevice.getName() + "配对并连接?";
} else {
msg = "是否与设备" + blueDevice.getName() + "连接?";
}
showDailog(msg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
/**
* 当前需要配对的蓝牙设备
*/
currentBluetoothDevice = blueDevice.getDevice();
/**
* 还没有配对
*/
if (blueDevice.getDevice().getBondState() != BluetoothDevice.BOND_BONDED) {
startPariBlue(blueDevice);
} else {
/**
* 完成配对的,直接连接
*/
contectBuleDevices();
}
showProgressDailog();
}
});
}
});
/**
* 长按取消配对
*/
lsBlue.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
List<BlueDevice> listDevices = blueAdapter.getListDevices();
final BlueDevice blueDevices = listDevices.get(i);
/**
* 还没有配对
*/
if (blueDevices.getDevice().getBondState() != BluetoothDevice.BOND_BONDED) {
return false;
/**
* 完成配对的
*/
} else {
showDailog("是否取消" + blueDevices.getName() + "配对?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
BlueUtils.unpairDevice(blueDevices.getDevice());
}
});
}
return false;
}
});
}
@Override
public void onClick(View view) {
if (mBluetoothAdapter == null)
return;
switch(view.getId()) {
case R.id.btn_start:
/**
* 如果本地蓝牙没有开启,则开启
*/
if (!mBluetoothAdapter.isEnabled()) {
// 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择,比如用户单击了Yes开启,
// 那么将会收到RESULT_OK的结果,
// 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(mIntent, ENABLE_BLUE);
} else {
Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
getBondedDevices();
}
break;
case R.id.btn_public:
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
// 180可见时间
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);
startActivity(intent);
break;
case R.id.btn_search:
showProgressDailog();
// 如果正在搜索,就先取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
mBluetoothAdapter.startDiscovery();
break;
case R.id.btn_stop:
/**
* 关闭蓝牙
*/
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
break;
case R.id.btn_play:
AudioUtils.INSTANCE.playMedai(MainActivity.this);
break;
case R.id.btn_stop_play:
AudioUtils.INSTANCE.stopPlay();
break;
default:
break;
}
}
/**
* 开始配对蓝牙设备
*
* @param blueDevice
*/
private void startPariBlue(BlueDevice blueDevice) {
BlueUtils blueUtils = new BlueUtils(blueDevice);
blueUtils.doPair();
}
/**
* 取消配对蓝牙设备
*
* @param blueDevice
*/
private void stopPariBlue(BlueDevice blueDevice) {
BlueUtils.unpairDevice(blueDevice.getDevice());
}
/**
* 开始连接蓝牙设备
*/
private void contectBuleDevices() {
/**
* 使用A2DP协议连接设备
*/
mBluetoothAdapter.getProfileProxy(this, mProfileServiceListener, BluetoothProfile.A2DP);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENABLE_BLUE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "蓝牙开启成功", Toast.LENGTH_SHORT).show();
getBondedDevices();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "蓝牙开始失败", Toast.LENGTH_SHORT).show();
}
} else {
}
}
/**
* 获取所有已经绑定的蓝牙设备并显示
*/
private void getBondedDevices() {
if (!setDevices.isEmpty())
setDevices.clear();
devices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice bluetoothDevice : devices) {
BlueDevice blueDevice = new BlueDevice();
blueDevice.setName(bluetoothDevice.getName());
blueDevice.setAddress(bluetoothDevice.getAddress());
blueDevice.setDevice(bluetoothDevice);
blueDevice.setStatus("已配对");
setDevices.add(blueDevice);
}
if (blueAdapter == null) {
blueAdapter = new BlueAdapter(this, setDevices);
lsBlue.setAdapter(blueAdapter);
} else {
blueAdapter.setSetDevices(setDevices);
blueAdapter.notifyDataSetChanged();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
ButterKnife.unbind(this);
if (a2dp != null) {
a2dp = null;
}
if (mProfileServiceListener != null) {
mProfileServiceListener = null;
}
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/**
* 搜索到的蓝牙设备
*/
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 搜索到的不是已经配对的蓝牙设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
BlueDevice blueDevice = new BlueDevice();
blueDevice.setName(device.getName());
blueDevice.setAddress(device.getAddress());
blueDevice.setDevice(device);
setDevices.add(blueDevice);
blueAdapter.setSetDevices(setDevices);
blueAdapter.notifyDataSetChanged();
Log.d(MAINACTIVITY, "搜索结果......" + device.getName());
}
/**
* 当绑定的状态改变时
*/
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch(device.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.d(MAINACTIVITY, "正在配对......");
break;
case BluetoothDevice.BOND_BONDED:
Log.d(MAINACTIVITY, "完成配对");
hideProgressDailog();
/**
* 开始连接
*/
contectBuleDevices();
break;
case BluetoothDevice.BOND_NONE:
Log.d(MAINACTIVITY, "取消配对");
Toast.makeText(MainActivity.this, "成功取消配对", Toast.LENGTH_SHORT).show();
getBondedDevices();
break;
default:
break;
}
/**
* 搜索完成
*/
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
setProgressBarIndeterminateVisibility(false);
Log.d(MAINACTIVITY, "搜索完成......");
hideProgressDailog();
}
}
};
/**
* 连接蓝牙设备(通过监听蓝牙协议的服务,在连接服务的时候使用BluetoothA2dp协议)
*/
private BluetoothProfile.ServiceListener mProfileServiceListener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceDisconnected(int profile) {
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
try {
if (profile == BluetoothProfile.HEADSET) {
// bh = (BluetoothHeadset) proxy;
// if (bh.getConnectionState(mTouchObject.bluetoothDevice) != BluetoothProfile.STATE_CONNECTED){
// bh.getClreplaced()
// .getMethod("connect", BluetoothDevice.clreplaced)
// .invoke(bh, mTouchObject.bluetoothDevice);
// }
} else if (profile == BluetoothProfile.A2DP) {
/**
* 使用A2DP的协议连接蓝牙设备(使用了反射技术调用连接的方法)
*/
a2dp = (BluetoothA2dp) proxy;
if (a2dp.getConnectionState(currentBluetoothDevice) != BluetoothProfile.STATE_CONNECTED) {
a2dp.getClreplaced().getMethod("connect", BluetoothDevice.clreplaced).invoke(a2dp, currentBluetoothDevice);
Toast.makeText(MainActivity.this, "请播放音乐", Toast.LENGTH_SHORT).show();
getBondedDevices();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}