Java Code Examples for android.media.AudioManager#setMode()

The following examples show how to use android.media.AudioManager#setMode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MsgListAdapter.java    From aurora-imui with MIT License 6 votes vote down vote up
public void setAudioPlayByEarPhone(int state) {
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    // 外放模式
    if (state == 0) {
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(true);
        // 耳机模式
    } else if (state == 1) {
        audioManager.setSpeakerphoneOn(false);
        // 听筒模式
    } else {
        audioManager.setSpeakerphoneOn(false);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume, AudioManager.STREAM_VOICE_CALL);
    }
}
 
Example 2
Source File: VOIPVoiceActivity.java    From voip_android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
}
 
Example 3
Source File: SignalAudioManager.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public void stop(boolean playDisconnected) {
  AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);

  incomingRinger.stop();
  outgoingRinger.stop();

  if (playDisconnected) {
    soundPool.play(disconnectedSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
  }

  if (audioManager.isBluetoothScoOn()) {
    audioManager.setBluetoothScoOn(false);
    audioManager.stopBluetoothSco();
  }

  audioManager.setSpeakerphoneOn(false);
  audioManager.setMicrophoneMute(false);
  audioManager.setMode(AudioManager.MODE_NORMAL);
  audioManager.abandonAudioFocus(null);
}
 
Example 4
Source File: AssistantService.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(AudioManager audioManager) {
    if (voiceMediator.isBlueToothHeadSet()) {
        if (!voiceMediator.isSuportA2DP()) {
            if (audioManager.getMode() != AudioManager.MODE_NORMAL) {
                Log.e(TAG, "playInChannel>>setMode(AudioManager.MODE_NORMAL)");
                audioManager.setMode(AudioManager.MODE_NORMAL);
            }
            if (audioManager.isBluetoothScoOn()) {
                audioManager.setBluetoothScoOn(false);
                audioManager.stopBluetoothSco();
            }
        } else {
            if (!audioManager.isBluetoothA2dpOn()) {
                Log.e(TAG, "playInChannel>>setBluetoothA2dpOn(true)");
                audioManager.setBluetoothA2dpOn(true);
            }
        }
    }
}
 
Example 5
Source File: ListAdapter.java    From jmessage-android-uikit with MIT License 6 votes vote down vote up
public void setAudioPlayByEarPhone(int state) {
    AudioManager audioManager = (AudioManager) mContext
            .getSystemService(Context.AUDIO_SERVICE);
    int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    if (state == 0) {
        mIsEarPhoneOn = false;
        audioManager.setSpeakerphoneOn(true);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                AudioManager.STREAM_VOICE_CALL);
        Log.i(TAG, "set SpeakerphoneOn true!");
    } else {
        mIsEarPhoneOn = true;
        audioManager.setSpeakerphoneOn(false);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume,
                AudioManager.STREAM_VOICE_CALL);
        Log.i(TAG, "set SpeakerphoneOn false!");
    }
}
 
Example 6
Source File: Ringer.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param audioManager 
 * 
 */
public void startRinging(AudioManager audioManager) {
    if(ringtone != null) {
        Log.d(THIS_FILE, "Starting ring with " + ringtone.getTitle(context));
        Message msg = ringerWorker.obtainMessage(RingWorkerHandler.PROGRESS_RING);
        msg.arg1 = RingWorkerHandler.PROGRESS_RING;
        Log.d(THIS_FILE, "Starting ringer...");
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        ringerWorker.sendMessage(msg);
    }
}
 
Example 7
Source File: SignalAudioManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: SignalAudioManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void stop(boolean playDisconnected) {
  AudioManager audioManager = ServiceUtil.getAudioManager(context);

  incomingRinger.stop();
  outgoingRinger.stop();

  if (playDisconnected) {
    soundPool.play(disconnectedSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
  }

  audioManager.setMode(AudioManager.MODE_NORMAL);

  audioManagerCompat.abandonCallAudioFocus();
}
 
Example 9
Source File: IflySynthesizer.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
/**
   * 设置默认的合成引擎
   *
   * @param type
   */
  private void setDefaultSynthesizerParam(NetType type) {
      if (isSpeaking()) {
          Log.e(TAG, "播放当中切换播放引擎失败");
          return;
      }
      synthesizer.setParameter(SpeechConstant.SPEED, Integer.toString(mVoiceConfig.getVolSpeed()));
      synthesizer.setParameter(SpeechConstant.VOLUME, Integer.toString(mVoiceConfig.getVolume()));
      synthesizer.setParameter(SpeechConstant.VOICE_NAME, mVoiceConfig.getVolName());
      synthesizer.setParameter("rdn", "0");
      synthesizer.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "0");
      if (mediator.isBlueToothHeadSet()) {
          synthesizer.setParameter(SpeechConstant.STREAM_TYPE, Integer.toString(AudioManager.STREAM_VOICE_CALL));
      } else {
          synthesizer.setParameter(SpeechConstant.STREAM_TYPE, Integer.toString(AudioManager.STREAM_MUSIC));
          AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
          if (am.getMode() != AudioManager.MODE_NORMAL) {
              am.setMode(AudioManager.MODE_NORMAL);
          }
      }
      //synthesizer.setParameter(SpeechConstant.ENGINE_TYPE, VoiceConfig.getSynEngineType());
      /*if(type==NetType.NETWORK_TYPE_NONE||type==NetType.NETWORK_TYPE_2G){//网络关闭的状态下启动离线识别
          Log.e(TAG, "离线。。。。。。。。。。。。。。。。。。。");
	synthesizer.setParameter(SpeechConstant.SPEED, OFFLINE_ENGINE_SPPED);
	synthesizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
	synthesizer.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
	isLocalEngine=true;
}
else{*/
      Log.e(TAG, "在线。。。。。。。。。。。。。。。。。。。");
      //synthesizer.setParameter(SpeechConstant.SPEED,"70");
      synthesizer.setParameter(SpeechConstant.VOICE_NAME, mVoiceConfig.getVolName());
      //synthesizer.setParameter(SpeechConstant.VOICE_NAME, ChatRobot.isInit()&&ChatRobot.getInstance().getMode()==ChatConstant.CHILDREN_MODE?"vinn":"vixq");
      synthesizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
      //}
  }
 
Example 10
Source File: ToneManager.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: MainActivity.java    From owt-client-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
            | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_main);

    fullScreen = true;
    bottomView = findViewById(R.id.bottom_bar);
    fragmentContainer = findViewById(R.id.fragment_container);
    leftBtn = findViewById(R.id.multi_func_btn_left);
    leftBtn.setOnClickListener(joinRoom);
    rightBtn = findViewById(R.id.multi_func_btn_right);
    rightBtn.setOnClickListener(settings);
    subscribeBtn = findViewById(R.id.multi_func_btn_subscribe);
    subscribeBtn.setOnClickListener(subscribe);
    subscribeBtn.setVisibility(View.GONE);
    unSubscribeBtn = findViewById(R.id.multi_func_btn_unsubscribe);
    unSubscribeBtn.setOnClickListener(unSubscribe);
    unSubscribeBtn.setVisibility(View.GONE);
    middleBtn = findViewById(R.id.multi_func_btn_middle);
    middleBtn.setOnClickListener(shareScreen);
    middleBtn.setVisibility(View.GONE);

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

    loginFragment = new LoginFragment();
    switchFragment(loginFragment);

    initConferenceClient();
}
 
Example 12
Source File: SilentOnAction.java    From beaconloc with Apache License 2.0 5 votes vote down vote up
@Override
public String execute(Context context) {
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        mRingerMode = AudioManager.RINGER_MODE_NORMAL;
    } else if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
        audioManager.setMode(AudioManager.RINGER_MODE_SILENT);
        mRingerMode = AudioManager.RINGER_MODE_VIBRATE;
    }
    PreferencesUtil.setSilentModeProfile(context, mRingerMode);
    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    return super.execute(context);
}
 
Example 13
Source File: ToneManager.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
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);
		}
	}
}
 
Example 15
Source File: EaseChatRowVoicePlayClickListener.java    From Social with Apache License 2.0 4 votes vote down vote up
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();
	}
}
 
Example 16
Source File: CallActivity.java    From sealrtc-android with MIT License 4 votes vote down vote up
@Override
public void onNotifyHeadsetState(boolean connected, int type) {
    try {
        if (connected) {
            HeadsetPlugReceiverState = true;
            if (type == 0) {
                startBluetoothSco();
            }
            if (null != btnMuteSpeaker) {
                btnMuteSpeaker.setBackgroundResource(R.drawable.img_capture_gray);
                btnMuteSpeaker.setSelected(false);
                btnMuteSpeaker.setEnabled(false);
                btnMuteSpeaker.setClickable(false);
                audioManager.onToggleSpeaker(false);
            }
        } else {
            if (type == 1 && BluetoothUtil.hasBluetoothA2dpConnected()) {
                return;
            }
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (am != null) {
                if (am.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
                    am.setMode(AudioManager.MODE_IN_COMMUNICATION);
                }
                if (type == 0) {
                    am.stopBluetoothSco();
                    am.setBluetoothScoOn(false);
                    am.setSpeakerphoneOn(!muteSpeaker);
                } else {
                    RCRTCEngine.getInstance().enableSpeaker(!this.muteSpeaker);
                }
                audioManager.onToggleSpeaker(!muteSpeaker);
            }
            if (null != btnMuteSpeaker) {
                btnMuteSpeaker.setBackgroundResource(R.drawable.selector_checkbox_capture);
                btnMuteSpeaker.setSelected(false);
                btnMuteSpeaker.setEnabled(true);
                btnMuteSpeaker.setClickable(true);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: MainActivity.java    From krankygeek with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(true);

    PeerConnectionFactory.initializeAndroidGlobals(
            this,  // Context
            true,  // Audio Enabled
            true,  // Video Enabled
            true,  // Hardware Acceleration Enabled
            null); // Render EGL Context

    peerConnectionFactory = new PeerConnectionFactory();

    VideoCapturerAndroid vc = VideoCapturerAndroid.create(VideoCapturerAndroid.getNameOfFrontFacingDevice(), null);

    localVideoSource = peerConnectionFactory.createVideoSource(vc, new MediaConstraints());
    VideoTrack localVideoTrack = peerConnectionFactory.createVideoTrack(VIDEO_TRACK_ID, localVideoSource);
    localVideoTrack.setEnabled(true);

    AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
    AudioTrack localAudioTrack = peerConnectionFactory.createAudioTrack(AUDIO_TRACK_ID, audioSource);
    localAudioTrack.setEnabled(true);

    localMediaStream = peerConnectionFactory.createLocalMediaStream(LOCAL_STREAM_ID);
    localMediaStream.addTrack(localVideoTrack);
    localMediaStream.addTrack(localAudioTrack);

    GLSurfaceView videoView = (GLSurfaceView) findViewById(R.id.glview_call);

    VideoRendererGui.setView(videoView, null);
    try {
        otherPeerRenderer = VideoRendererGui.createGui(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
        VideoRenderer renderer = VideoRendererGui.createGui(50, 50, 50, 50, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
        localVideoTrack.addRenderer(renderer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: VoIPBaseService.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
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);
		}
	}
}
 
Example 19
Source File: EaseChatRowVoicePlayClickListener.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
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();
	}
}
 
Example 20
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@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.didEndCall);
		}
	});
	if (tgVoip != null) {
		updateTrafficStats();
		StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), (int) (getCallDuration() / 1000) % 5);
		onTgVoipPreStop();
		onTgVoipStop(tgVoip.stop());
		prevTrafficStats = null;
		callStartTime = 0;
		tgVoip = null;
	}
	cpuWakelock.release();
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		if(isBtHeadsetConnected && !playingSound){
			am.stopBluetoothSco();
			am.setBluetoothScoOn(false);
			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(!didDeleteConnectionServiceContact)
			ContactsController.getInstance(currentAccount).deleteConnectionServiceContact();
		if(systemCallConnection!=null && !playingSound){
			systemCallConnection.destroy();
		}
	}

	ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false);
	VoIPHelper.lastCallTime=System.currentTimeMillis();
}