android 5.1 系统音频的切换

1, 获取各种音量

首先获取音频管理类AudioManager

AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

获取通话最大/当前音量

int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
int current = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);


获取系统最大/当前音量

max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
current = mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);


获取音乐最大/当前音量

max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);


获取提示音最大/当前音量

max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
current = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);


 

2, 打开/关闭扬声器

private void openSpeaker() {
	  try{
	    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
	    audioManager.setMode(AudioManager.ROUTE_SPEAKER);	      
     currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
	   if(!audioManager.isSpeakerphoneOn()) {
	        audioManager.setMode(AudioManager.MODE_IN_CALL);
	        audioManager.setSpeakerphoneOn(true);
	        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
	             audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
	             AudioManager.STREAM_VOICE_CALL);
	      }
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	}


public void closeSpeaker() {
	  try {
	    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
	      if(audioManager != null) {
	        if(audioManager.isSpeakerphoneOn()) {
	          audioManager.setSpeakerphoneOn(false);
	          audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,currVolume,
	              AudioManager.STREAM_VOICE_CALL);
	        }
	      }
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	}


3, 蓝牙耳机输出

如果连接了蓝牙耳机,需要将声音从蓝牙耳机输出,代码如下:

private void openHeadset() {
    	try{
            AudioManager audioManager = (AudioManager) 
                      getSystemService(Context.AUDIO_SERVICE);
  	      audioManager.setSpeakerphoneOn(false);
  	      audioManager.setMode(AudioManager.ROUTE_BLUETOOTH);
  	      currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
  	      Log.d("fang ","audioManager " + audioManager.isSpeakerphoneOn());
  	      if(!audioManager.isSpeakerphoneOn()) {
  	          	 audioManager.setMode(AudioManager.MODE_IN_CALL);
  	            audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
  	                 audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
  	                 AudioManager.STREAM_VOICE_CALL);
  	      }
  	    } catch (Exception e) {
  	      e.printStackTrace();
  	    }
	}


打开/关闭不同音频通道原理和方法都一样,只是AudioManager的参数不一样而已。

 

最后必须在AndroidManifest.xml 文件中添加权限



 

 

你可能感兴趣的:(---【实践】)