下面列出了android.media.AudioManager#setSpeakerphoneOn ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG, "Headset is unplugged");
audioManager.setSpeakerphoneOn(true);
break;
case 1:
Log.d(TAG, "Headset is plugged");
audioManager.setSpeakerphoneOn(false);
break;
default:
Log.d(TAG, "I have no idea what the headset state is");
}
}
}
private void handleWiredHeadsetChange(Intent intent) {
Log.i(TAG, "handleWiredHeadsetChange...");
if ((activePeer != null) &&
(activePeer.getState() == CallState.CONNECTED ||
activePeer.getState() == CallState.DIALING ||
activePeer.getState() == CallState.RECEIVED_BUSY ||
activePeer.getState() == CallState.REMOTE_RINGING))
{
AudioManager audioManager = ServiceUtil.getAudioManager(this);
boolean present = intent.getBooleanExtra(EXTRA_AVAILABLE, false);
if (present && audioManager.isSpeakerphoneOn()) {
audioManager.setSpeakerphoneOn(false);
audioManager.setBluetoothScoOn(false);
} else if (!present && !audioManager.isSpeakerphoneOn() && !audioManager.isBluetoothScoOn() && localCameraState.isEnabled()) {
audioManager.setSpeakerphoneOn(true);
}
sendMessage(viewModelStateFor(activePeer), activePeer, localCameraState, remoteVideoEnabled, bluetoothAvailable, microphoneEnabled, isRemoteVideoOffer);
}
}
public void startOutgoingRinger(OutgoingRinger.Type type) {
AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);
audioManager.setMicrophoneMute(false);
if (type == OutgoingRinger.Type.SONAR) {
audioManager.setSpeakerphoneOn(false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
} else {
audioManager.setMode(AudioManager.MODE_IN_CALL);
}
outgoingRinger.start(type);
}
public void startCommunication(boolean preserveSpeakerphone) {
AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);
incomingRinger.stop();
outgoingRinger.stop();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
} else {
audioManager.setMode(AudioManager.MODE_IN_CALL);
}
if (!preserveSpeakerphone) {
audioManager.setSpeakerphoneOn(false);
}
soundPool.play(connectedSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
@Override
protected void startStream() {
super.startStream();
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
am.setSpeakerphoneOn(false);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
this.duration = 0;
this.durationTimer = new Timer() {
@Override
protected void fire() {
VOIPVoiceActivity.this.duration += 1;
String text = String.format("%02d:%02d", VOIPVoiceActivity.this.duration/60, VOIPVoiceActivity.this.duration%60);
durationTextView.setText(text);
}
};
this.durationTimer.setTimer(uptimeMillis()+1000, 1000);
this.durationTimer.resume();
}
public void startIncomingRinger(@Nullable Uri ringtoneUri, boolean vibrate) {
AudioManager audioManager = ServiceUtil.getAudioManager(context);
boolean speaker = !audioManager.isWiredHeadsetOn() && !audioManager.isBluetoothScoOn();
audioManager.setMode(AudioManager.MODE_RINGTONE);
audioManager.setMicrophoneMute(false);
audioManager.setSpeakerphoneOn(speaker);
incomingRinger.start(ringtoneUri, vibrate);
}
public void startCommunication(boolean preserveSpeakerphone) {
AudioManager audioManager = ServiceUtil.getAudioManager(context);
incomingRinger.stop();
outgoingRinger.stop();
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
if (!preserveSpeakerphone) {
audioManager.setSpeakerphoneOn(false);
}
soundPool.play(connectedSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
private void configureAudioManagerForCall(final Set<Media> media) {
if (appRtcAudioManagerHasControl) {
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": do not configure audio manager because RTC has control");
return;
}
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager == null) {
return;
}
final boolean isSpeakerPhone = media.contains(Media.VIDEO);
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": putting AudioManager into communication mode. speaker=" + isSpeakerPhone);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(isSpeakerPhone);
}
private void resetAudioManager() {
if (appRtcAudioManagerHasControl) {
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": do not reset audio manager because RTC has control");
return;
}
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager == null) {
return;
}
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": putting AudioManager back into normal mode");
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(false);
}
private void resetAudioManager() {
if (appRtcAudioManagerHasControl) {
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": do not reset audio manager because RTC has control");
return;
}
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager == null) {
return;
}
Log.d(Config.LOGTAG, ToneManager.class.getName() + ": putting AudioManager back into normal mode");
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(false);
}
@PhonkMethod(description = "Routes the audio through the speakers", example = "media.playSound(fileName);")
@PhonkMethodParam(params = {""})
public void audioOnSpeakers(boolean b) {
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(!b);
}
protected void updateBluetoothHeadsetState(boolean connected){
if(connected==isBtHeadsetConnected)
return;
if(BuildVars.LOGS_ENABLED)
FileLog.d("updateBluetoothHeadsetState: "+connected);
isBtHeadsetConnected=connected;
final AudioManager am=(AudioManager)getSystemService(AUDIO_SERVICE);
if(connected && !isRinging() && currentState!=0){
if(bluetoothScoActive){
if(BuildVars.LOGS_ENABLED)
FileLog.d("SCO already active, setting audio routing");
am.setSpeakerphoneOn(false);
am.setBluetoothScoOn(true);
}else{
if(BuildVars.LOGS_ENABLED)
FileLog.d("startBluetoothSco");
needSwitchToBluetoothAfterScoActivates=true;
// some devices ignore startBluetoothSco when called immediately after the headset is connected, so delay it
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
try {
am.startBluetoothSco();
} catch (Throwable ignore) {
}
}
}, 500);
}
}else{
bluetoothScoActive=false;
}
for (StateListener l : stateListeners)
l.onAudioSettingsChanged();
}
private void setUseFrontSpeaker(boolean value) {
useFrontSpeaker = value;
AudioManager audioManager = NotificationsController.audioManager;
if (useFrontSpeaker) {
audioManager.setBluetoothScoOn(false);
audioManager.setSpeakerphoneOn(false);
} else {
audioManager.setSpeakerphoneOn(true);
}
}
protected void configureDeviceForCall() {
needPlayEndSound = true;
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
if(!USE_CONNECTION_SERVICE){
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
if(isBluetoothHeadsetConnected() && hasEarpiece()){
switch(audioRouteToSet){
case AUDIO_ROUTE_BLUETOOTH:
if(!bluetoothScoActive){
needSwitchToBluetoothAfterScoActivates=true;
try {
am.startBluetoothSco();
} catch (Throwable ignore) {
}
}else{
am.setBluetoothScoOn(true);
am.setSpeakerphoneOn(false);
}
break;
case AUDIO_ROUTE_EARPIECE:
am.setBluetoothScoOn(false);
am.setSpeakerphoneOn(false);
break;
case AUDIO_ROUTE_SPEAKER:
am.setBluetoothScoOn(false);
am.setSpeakerphoneOn(true);
break;
}
}else if(isBluetoothHeadsetConnected()){
am.setBluetoothScoOn(speakerphoneStateToSet);
}else{
am.setSpeakerphoneOn(speakerphoneStateToSet);
}
}/*else{
if(isBluetoothHeadsetConnected() && hasEarpiece()){
switch(audioRouteToSet){
case AUDIO_ROUTE_BLUETOOTH:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
break;
case AUDIO_ROUTE_EARPIECE:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
break;
case AUDIO_ROUTE_SPEAKER:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
break;
}
}else{
if(hasEarpiece())
systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER);
else
systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH);
}
}*/
updateOutputGainControlState();
audioConfigured=true;
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
try{
if(proximity!=null){
proximityWakelock=((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
}
}catch(Exception x){
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error initializing proximity sensor", x);
}
}
}
public static void handsfree(Context context) {
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
manager.setMode(AudioManager.MODE_IN_CALL);
manager.setSpeakerphoneOn(true);
Alarm.loudest(context, AudioManager.STREAM_VOICE_CALL);
}
public void playVoice(String filePath) {
if (!(new File(filePath).exists())) {
return;
}
playMsgId = message.getMsgId();
AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
mediaPlayer = new MediaPlayer();
if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
} else {
audioManager.setSpeakerphoneOn(false);// 关闭扬声器
// 把声音设定成Earpiece(听筒)出来,设定为正在通话中
audioManager.setMode(AudioManager.MODE_IN_CALL);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.release();
mediaPlayer = null;
stopPlayVoice(); // stop animation
}
});
isPlaying = true;
currentPlayListener = this;
mediaPlayer.start();
showAnimation();
// 如果是接收的消息
if (message.direct() == EMMessage.Direct.RECEIVE) {
if (!message.isAcked() && chatType == ChatType.Chat) {
// 告知对方已读这条消息
EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
}
if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
// 隐藏自己未播放这条语音消息的标志
iv_read_status.setVisibility(View.INVISIBLE);
message.setListened(true);
EMClient.getInstance().chatManager().setMessageListened(message);
}
}
} catch (Exception e) {
System.out.println();
}
}
public void playVoice(String filePath) {
if (!(new File(filePath).exists())) {
return;
}
playMsgId = message.getMsgId();
AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
mediaPlayer = new MediaPlayer();
//---------------------------
//EaseUI.getInstance();
//---------------------------
if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
} else {
audioManager.setSpeakerphoneOn(false);// 关闭扬声器
// 把声音设定成Earpiece(听筒)出来,设定为正在通话中
audioManager.setMode(AudioManager.MODE_IN_CALL);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.release();
mediaPlayer = null;
stopPlayVoice(); // stop animation
}
});
isPlaying = true;
currentPlayListener = this;
mediaPlayer.start();
showAnimation();
// 如果是接收的消息
if (message.direct() == EMMessage.Direct.RECEIVE) {
if (!message.isAcked() && chatType == ChatType.Chat) {
// 告知对方已读这条消息
EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
}
if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
// 隐藏自己未播放这条语音消息的标志
iv_read_status.setVisibility(View.INVISIBLE);
message.setListened(true);
EMClient.getInstance().chatManager().setMessageListened(message);
}
}
} catch (Exception e) {
System.out.println();
}
}
@Override
public void onDestroy() {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("=============== VoIPService STOPPING ===============");
}
stopForeground(true);
stopRinging();
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.appDidLogout);
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (proximity != null) {
sm.unregisterListener(this);
}
if (proximityWakelock != null && proximityWakelock.isHeld()) {
proximityWakelock.release();
}
unregisterReceiver(receiver);
if(timeoutRunnable!=null){
AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
timeoutRunnable=null;
}
super.onDestroy();
sharedInstance = null;
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didEndedCall);
}
});
if (controller != null && controllerStarted) {
lastKnownDuration = controller.getCallDuration();
updateStats();
StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), (int) (lastKnownDuration / 1000) % 5);
onControllerPreRelease();
controller.release();
controller = null;
}
cpuWakelock.release();
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
if(!USE_CONNECTION_SERVICE){
if(isBtHeadsetConnected && !playingSound){
am.stopBluetoothSco();
am.setSpeakerphoneOn(false);
}
try{
am.setMode(AudioManager.MODE_NORMAL);
}catch(SecurityException x){
if(BuildVars.LOGS_ENABLED){
FileLog.e("Error setting audio more to normal", x);
}
}
am.abandonAudioFocus(this);
}
am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));
if (haveAudioFocus)
am.abandonAudioFocus(this);
if (!playingSound)
soundPool.release();
if(USE_CONNECTION_SERVICE){
if(systemCallConnection!=null && !playingSound){
systemCallConnection.destroy();
}
}
ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false);
VoIPHelper.lastCallTime=System.currentTimeMillis();
}
protected void configureDeviceForCall() {
needPlayEndSound = true;
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
if(!USE_CONNECTION_SERVICE){
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
if(isBluetoothHeadsetConnected() && hasEarpiece()){
switch(audioRouteToSet){
case AUDIO_ROUTE_BLUETOOTH:
if(!bluetoothScoActive){
needSwitchToBluetoothAfterScoActivates=true;
try {
am.startBluetoothSco();
} catch (Throwable ignore) {
}
}else{
am.setBluetoothScoOn(true);
am.setSpeakerphoneOn(false);
}
break;
case AUDIO_ROUTE_EARPIECE:
am.setBluetoothScoOn(false);
am.setSpeakerphoneOn(false);
break;
case AUDIO_ROUTE_SPEAKER:
am.setBluetoothScoOn(false);
am.setSpeakerphoneOn(true);
break;
}
}else if(isBluetoothHeadsetConnected()){
am.setBluetoothScoOn(speakerphoneStateToSet);
}else{
am.setSpeakerphoneOn(speakerphoneStateToSet);
}
}/*else{
if(isBluetoothHeadsetConnected() && hasEarpiece()){
switch(audioRouteToSet){
case AUDIO_ROUTE_BLUETOOTH:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
break;
case AUDIO_ROUTE_EARPIECE:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
break;
case AUDIO_ROUTE_SPEAKER:
systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
break;
}
}else{
if(hasEarpiece())
systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER);
else
systemCallConnection.setAudioRoute(!speakerphoneStateToSet ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH);
}
}*/
updateOutputGainControlState();
audioConfigured=true;
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
try{
if(proximity!=null){
proximityWakelock=((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
}
}catch(Exception x){
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error initializing proximity sensor", x);
}
}
}
public void playVoice(String filePath) {
if (!(new File(filePath).exists())) {
return;
}
playMsgId = message.getMsgId();
AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
mediaPlayer = new MediaPlayer();
if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
} else {
audioManager.setSpeakerphoneOn(false);// 关闭扬声器
// 把声音设定成Earpiece(听筒)出来,设定为正在通话中
audioManager.setMode(AudioManager.MODE_IN_CALL);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.release();
mediaPlayer = null;
stopPlayVoice(); // stop animation
}
});
isPlaying = true;
currentPlayListener = this;
mediaPlayer.start();
showAnimation();
// 如果是接收的消息
if (message.direct() == EMMessage.Direct.RECEIVE) {
if (!message.isAcked() && chatType == ChatType.Chat) {
// 告知对方已读这条消息
EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
}
if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
// 隐藏自己未播放这条语音消息的标志
iv_read_status.setVisibility(View.INVISIBLE);
message.setListened(true);
EMClient.getInstance().chatManager().setMessageListened(message);
}
}
} catch (Exception e) {
System.out.println();
}
}