public void playVoice(String filePath) {
    if (!(new File(filePath).exists())) {
      return;
    }
    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

    mediaPlayer = new MediaPlayer();
    if (EMChatManager.getInstance().getChatOptions().getUseSpeaker()) {
      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;
      currentMessage = message;
      mediaPlayer.start();
      showAnimation();
      try {
        // 如果是接收的消息
        if (!message.isAcked && message.direct == EMMessage.Direct.RECEIVE) {
          message.isAcked = true;
          if (iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
            // 隐藏自己未播放这条语音消息的标志
            iv_read_status.setVisibility(View.INVISIBLE);
            EMChatDB.getInstance().updateMessageAck(message.getMsgId(), true);
          }
          // 告知对方已读这条消息
          if (chatType != ChatType.GroupChat)
            EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
        }
      } catch (Exception e) {
        message.isAcked = false;
      }
    } catch (Exception e) {
    }
  }
 @Override
 public void onDestroy() {
   Log.i(TAG, "onDestroy");
   unregisterMyBroadcastService();
   mamanager.setMode(AudioManager.MODE_NORMAL);
   super.onDestroy();
 }
  public void init() {
    Log.d(TAG, "init");
    if (initialized) {
      return;
    }

    // Store current audio state so we can restore it when close() is called.
    savedAudioMode = audioManager.getMode();
    savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
    savedIsMicrophoneMute = audioManager.isMicrophoneMute();

    // Request audio focus before making any device switch.
    audioManager.requestAudioFocus(
        null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

    // Start by setting RINGTONE as default audio mode. The native WebRTC
    // audio layer will switch to COMMUNICATION mode when the first streaming
    // session starts and return to RINGTONE mode when all streaming stops.
    audioManager.setMode(AudioManager.MODE_RINGTONE);

    // Always disable microphone mute during a WebRTC call.
    setMicrophoneMute(false);

    // Do initial selection of audio device. This setting can later be changed
    // either by adding/removing a wired headset or by covering/uncovering the
    // proximity sensor.
    updateAudioDeviceState(hasWiredHeadset());

    // Register receiver for broadcast intents related to adding/removing a
    // wired headset (Intent.ACTION_HEADSET_PLUG).
    registerForWiredHeadsetIntentBroadcast();

    initialized = true;
  }
  public void init() {
    Log.d(TAG, "init");
    if (initialized) {
      return;
    }

    // Store current audio state so we can restore it when close() is called.
    savedAudioMode = audioManager.getMode();
    savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
    savedIsMicrophoneMute = audioManager.isMicrophoneMute();

    // Request audio focus before making any device switch.
    audioManager.requestAudioFocus(
        null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

    // Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
    // required to be in this mode when playout and/or recording starts for
    // best possible VoIP performance.
    // TODO(henrika): we migh want to start with RINGTONE mode here instead.
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

    // Always disable microphone mute during a WebRTC call.
    setMicrophoneMute(false);

    // Do initial selection of audio device. This setting can later be changed
    // either by adding/removing a wired headset or by covering/uncovering the
    // proximity sensor.
    updateAudioDeviceState(hasWiredHeadset());

    // Register receiver for broadcast intents related to adding/removing a
    // wired headset (Intent.ACTION_HEADSET_PLUG).
    registerForWiredHeadsetIntentBroadcast();

    initialized = true;
  }
Exemple #5
0
  /**
   * 播放拨号响铃
   *
   * @param sound
   * @param number
   */
  protected int playMakeCallSounds() {
    try {
      // 最大音量
      float audioMaxVolumn = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
      // 当前音量
      float audioCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_RING);
      float volumnRatio = audioCurrentVolumn / audioMaxVolumn;

      audioManager.setMode(AudioManager.MODE_RINGTONE);
      audioManager.setSpeakerphoneOn(false);

      // 播放
      int id =
          soundPool.play(
              outgoing, // 声音资源
              0.3f, // 左声道
              0.3f, // 右声道
              1, // 优先级,0最低
              -1, // 循环次数,0是不循环,-1是永远循环
              1); // 回放速度,0.5-2.0之间。1为正常速度
      return id;
    } catch (Exception e) {
      return -1;
    }
  }
  private void initData(Context context) {
    this.mContext = context;
    mActivity = (Activity) context;
    DisplayMetrics dm = new DisplayMetrics();
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    mDensity = dm.density;
    mWidth = dm.widthPixels;
    mInflater = LayoutInflater.from(mContext);
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_NORMAL);
    if (audioManager.isSpeakerphoneOn()) {
      audioManager.setSpeakerphoneOn(true);
    } else {
      audioManager.setSpeakerphoneOn(false);
    }
    mp.setAudioStreamType(AudioManager.STREAM_RING);
    mp.setOnErrorListener(
        new OnErrorListener() {

          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
          }
        });
  }
 @Override
 public void onClick(View v) {
   status = false;
   speaker.release();
   Log.d("VR", "Speaker released");
   am.setMode(AudioManager.MODE_NORMAL);
 }
 // 打开扬声器
 protected void openSpeakerOn() {
   try {
     if (!audioManager.isSpeakerphoneOn()) audioManager.setSpeakerphoneOn(true);
     audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Override
  public void onClick(View arg0) {
    // TODO 自动生成的方法存根
    switch (arg0.getId()) {
      case R.id.show_audio_chat_volume_big:
        if (ISSPEAKER == true) {
          audioManager.setMode(AudioManager.MODE_IN_CALL); // 把模式调成喇叭听筒模式
          ISSPEAKER = false;
        } else if (ISSPEAKER == false) {
          audioManager.setMode(AudioManager.MODE_NORMAL); // 把模式调成喇叭放音模式
          ISSPEAKER = true;
        }
        break;

      default:
        break;
    }
  }
 private void setAudioFocus(boolean focus) {
   if (focus) {
     previousAudioMode = audioManager.getMode();
     // Request audio focus before making any device switch.
     audioManager.requestAudioFocus(
         null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
     /*
      * Use MODE_IN_COMMUNICATION as the default audio mode. It is required
      * to be in this mode when playout and/or recording starts for the best
      * possible VoIP performance. Some devices have difficulties with
      * speaker mode if this is not set.
      */
     audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
   } else {
     audioManager.setMode(previousAudioMode);
     audioManager.abandonAudioFocus(null);
   }
 }
 @TestTargets({
   @TestTargetNew(
       level = TestLevel.COMPLETE,
       method = "setMode",
       args = {int.class}),
   @TestTargetNew(
       level = TestLevel.COMPLETE,
       method = "getMode",
       args = {})
 })
 public void testAccessMode() throws Exception {
   mAudioManager.setMode(MODE_RINGTONE);
   assertEquals(MODE_RINGTONE, mAudioManager.getMode());
   mAudioManager.setMode(MODE_IN_CALL);
   assertEquals(MODE_IN_CALL, mAudioManager.getMode());
   mAudioManager.setMode(MODE_NORMAL);
   assertEquals(MODE_NORMAL, mAudioManager.getMode());
 }
 public static void setMode(int mode) {
   Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
   edit.putBoolean(org.sipdroid.sipua.ui.Settings.PREF_SETMODE, true);
   edit.commit();
   AudioManager am = (AudioManager) Receiver.mContext.getSystemService(Context.AUDIO_SERVICE);
   if (Integer.parseInt(Build.VERSION.SDK) >= 5) {
     am.setSpeakerphoneOn(mode == AudioManager.MODE_NORMAL);
     if (samsung) RtpStreamSender.changed = true;
   } else am.setMode(mode);
 }
Exemple #13
0
  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (soundPool != null) soundPool.release();
    if (ringtone != null && ringtone.isPlaying()) ringtone.stop();
    audioManager.setMode(AudioManager.MODE_NORMAL);
    audioManager.setMicrophoneMute(false);

    if (callStateListener != null)
      EMChatManager.getInstance().removeCallStateChangeListener(callStateListener);
  }
 @Override
 protected void onDestroy() {
   // TODO Auto-generated method stub
   mContext.unregisterReceiver(broad);
   audioManager.setMode(AudioManager.MODE_NORMAL);
   if (player != null && player.isPlaying()) {
     player.stop();
     player.release();
     player = null;
   }
   super.onDestroy();
 }
 public static void restoreMode() {
   if (PreferenceManager.getDefaultSharedPreferences(Receiver.mContext)
       .getBoolean(
           org.sipdroid.sipua.ui.Settings.PREF_SETMODE,
           org.sipdroid.sipua.ui.Settings.DEFAULT_SETMODE)) {
     Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
     edit.putBoolean(org.sipdroid.sipua.ui.Settings.PREF_SETMODE, false);
     edit.commit();
     if (Receiver.pstn_state == null || Receiver.pstn_state.equals("IDLE")) {
       AudioManager am = (AudioManager) Receiver.mContext.getSystemService(Context.AUDIO_SERVICE);
       if (Integer.parseInt(Build.VERSION.SDK) >= 5) am.setSpeakerphoneOn(false);
       else am.setMode(AudioManager.MODE_NORMAL);
     }
   }
 }
Exemple #16
0
  // 关闭扬声器
  protected void closeSpeakerOn() {

    try {
      if (audioManager != null) {
        // int curVolume =
        // audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        if (audioManager.isSpeakerphoneOn()) audioManager.setSpeakerphoneOn(false);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        // audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
        // curVolume, AudioManager.STREAM_VOICE_CALL);

      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #17
0
  /**
   * <pre>
   * 打开扬声器
   * @param mContext
   * </pre>
   */
  public void OpenSpeaker(Context mContext) {

    try {
      AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
      audioManager.setMode(AudioManager.ROUTE_SPEAKER);
      currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

      if (!audioManager.isSpeakerphoneOn()) {
        audioManager.setSpeakerphoneOn(true);

        audioManager.setStreamVolume(
            AudioManager.STREAM_VOICE_CALL,
            audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
            AudioManager.STREAM_VOICE_CALL);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** Restore the state of the audio */
  @SuppressWarnings("deprecation")
  private final synchronized void restoreAudioState() {
    if (!prefs.getBoolean("isSavedAudioState", false)) {
      // If we have NEVER set, do not try to reset !
      return;
    }

    ContentResolver ctntResolver = service.getContentResolver();

    Settings.System.putInt(
        ctntResolver,
        Settings.System.WIFI_SLEEP_POLICY,
        prefs.getInt("savedWifiPolicy", Settings.System.WIFI_SLEEP_POLICY_DEFAULT));
    // audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
    // prefs.getInt("savedVibrateRing",
    // AudioManager.VIBRATE_SETTING_ONLY_SILENT));
    // audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
    // prefs.getInt("savedVibradeNotif", AudioManager.VIBRATE_SETTING_OFF));
    // audioManager.setRingerMode(prefs.getInt("savedRingerMode",
    // AudioManager.RINGER_MODE_NORMAL));

    int inCallStream = Compatibility.getInCallStream(userWantBluetooth);
    setStreamVolume(
        inCallStream,
        prefs.getInt("savedVolume", (int) (audioManager.getStreamMaxVolume(inCallStream) * 0.8)),
        0);

    int targetMode = getAudioTargetMode();
    if (service.getPrefs().useRoutingApi()) {
      audioManager.setRouting(
          targetMode,
          prefs.getInt("savedRoute", AudioManager.ROUTE_SPEAKER),
          AudioManager.ROUTE_ALL);
    } else {
      audioManager.setSpeakerphoneOn(prefs.getBoolean("savedSpeakerPhone", false));
    }
    audioManager.setMode(prefs.getInt("savedMode", AudioManager.MODE_NORMAL));

    Editor ed = prefs.edit();
    ed.putBoolean("isSavedAudioState", false);
    ed.commit();
  }
 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!");
   }
 }
  public void close() {
    Log.d(TAG, "close");
    if (!initialized) {
      return;
    }

    unregisterForWiredHeadsetIntentBroadcast();

    // Restore previously stored audio states.
    setSpeakerphoneOn(savedIsSpeakerPhoneOn);
    setMicrophoneMute(savedIsMicrophoneMute);
    audioManager.setMode(savedAudioMode);
    audioManager.abandonAudioFocus(null);

    if (proximitySensor != null) {
      proximitySensor.stop();
      proximitySensor = null;
    }

    initialized = false;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    receiveButton = (Button) findViewById(R.id.receive_button);
    stopButton = (Button) findViewById(R.id.stop_button);
    findViewById(R.id.receive_label);

    receiveButton.setOnClickListener(receiveListener);
    stopButton.setOnClickListener(stopListener);

    /*ForText
    recTV = (TextView) findViewById(R.id.rec_TV);
    recTV.setText("Ready To receive");
    */

    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    am.setMode(AudioManager.MODE_IN_CALL);
    am.setSpeakerphoneOn(false);
  }
 @Override
 public void onPrepared(MediaPlayer mediaPlayer) {
   System.out.println(sPhelper.getSongState() + "songstate==============");
   mediaPlayer.setOnCompletionListener(
       new OnCompletionListener() {
         public void onCompletion(MediaPlayer mp) {
           // cleanupPlayer(mp);
           System.out.println("=================:::::complete");
         }
       });
   mediaPlayer.setOnErrorListener(
       new OnErrorListener() {
         public boolean onError(MediaPlayer mp, int what, int extra) {
           //  cleanupPlayer(mp);
           System.out.println("=================:::::error");
           return true;
         }
       });
   if (sPhelper.getSongState() != null) {
     if (sPhelper.getSongState().equals("true")) {
       AudioManager audiomanager =
           (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
       audiomanager.setMode(AudioManager.MODE_NORMAL);
       audiomanager.setStreamVolume(
           AudioManager.STREAM_MUSIC,
           audiomanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
           0);
       audiomanager.adjustVolume(AudioManager.ADJUST_RAISE, 0);
       mediaPlayer.start();
       System.out.println(sPhelper.getSongState() + "=====================>>>>>shengyin");
       if (!mediaPlayer.isPlaying()) {
         mediaPlayer.release();
       }
     }
     if (sPhelper.getSongState().equals("false")) {
       mediaPlayer.release();
     }
   }
 }
  /** Set the audio mode as in call */
  @SuppressWarnings("deprecation")
  private synchronized void actualSetAudioInCall() {
    // Ensure not already set
    if (isSetAudioMode) {
      return;
    }
    stopRing();
    saveAudioState();

    // Set the rest of the phone in a better state to not interferate with
    // current call
    // Do that only if we were not already in silent mode
    /*
     * Not needed anymore with on flight gsm call capture
     * if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
     * audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
     * AudioManager.VIBRATE_SETTING_ON);
     * audioManager.setVibrateSetting(AudioManager
     * .VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
     * audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); }
     */

    // LOCKS

    // Wifi management if necessary
    ContentResolver ctntResolver = service.getContentResolver();
    Settings.System.putInt(
        ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);

    // Acquire wifi lock
    WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE);
    if (wifiLock == null) {
      wifiLock =
          wman.createWifiLock(
              (Compatibility.isCompatible(9))
                  ? WifiManager.WIFI_MODE_FULL_HIGH_PERF
                  : WifiManager.WIFI_MODE_FULL,
              "com.csipsimple.InCallLock");
      wifiLock.setReferenceCounted(false);
    }
    WifiInfo winfo = wman.getConnectionInfo();
    if (winfo != null) {
      DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState());
      // We assume that if obtaining ip addr, we are almost connected so
      // can keep wifi lock
      if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) {
        if (!wifiLock.isHeld()) {
          wifiLock.acquire();
        }
      }

      // This wake lock purpose is to prevent PSP wifi mode
      if (service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) {
        if (screenLock == null) {
          PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);
          screenLock =
              pm.newWakeLock(
                  PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
                  "com.csipsimple.onIncomingCall.SCREEN");
          screenLock.setReferenceCounted(false);
        }
        // Ensure single lock
        if (!screenLock.isHeld()) {
          screenLock.acquire();
        }
      }
    }

    if (!useWebRTCImpl) {
      // Audio routing
      int targetMode = getAudioTargetMode();
      Log.d(THIS_FILE, "Set mode audio in call to " + targetMode);

      if (service.getPrefs().generateForSetCall()) {
        boolean needOutOfSilent = (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT);
        if (needOutOfSilent) {
          audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_VOICE_CALL, 1);
        toneGenerator.startTone(41 /* ToneGenerator.TONE_CDMA_CONFIRM */);
        toneGenerator.stopTone();
        toneGenerator.release();
        // Restore silent mode
        if (needOutOfSilent) {
          audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
      }

      // Set mode
      if (targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) {
        // For galaxy S we need to set in call mode before to reset
        // stack
        audioManager.setMode(AudioManager.MODE_IN_CALL);
      }

      audioManager.setMode(targetMode);

      // Routing
      if (service.getPrefs().useRoutingApi()) {
        audioManager.setRouting(
            targetMode,
            userWantSpeaker ? AudioManager.ROUTE_SPEAKER : AudioManager.ROUTE_EARPIECE,
            AudioManager.ROUTE_ALL);
      } else {
        audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false);
      }

      audioManager.setMicrophoneMute(false);
      if (bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) {
        Log.d(THIS_FILE, "Try to enable bluetooth");
        bluetoothWrapper.setBluetoothOn(true);
      }

    } else {
      // WebRTC implementation for routing
      int apiLevel = Compatibility.getApiLevel();

      // SetAudioMode
      // ***IMPORTANT*** When the API level for honeycomb (H) has been
      // decided,
      // the condition should be changed to include API level 8 to H-1.
      if (android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) {
        // Set Samsung specific VoIP mode for 2.2 devices
        int mode = 4;
        audioManager.setMode(mode);
        if (audioManager.getMode() != mode) {
          Log.e(THIS_FILE, "Could not set audio mode for Samsung device");
        }
      }

      // SetPlayoutSpeaker
      if ((3 == apiLevel) || (4 == apiLevel)) {
        // 1.5 and 1.6 devices
        if (userWantSpeaker) {
          // route audio to back speaker
          audioManager.setMode(AudioManager.MODE_NORMAL);
        } else {
          // route audio to earpiece
          audioManager.setMode(AudioManager.MODE_IN_CALL);
        }
      } else {
        // 2.x devices
        if ((android.os.Build.BRAND.equalsIgnoreCase("samsung"))
            && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) {
          // Samsung 2.0, 2.0.1 and 2.1 devices
          if (userWantSpeaker) {
            // route audio to back speaker
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            audioManager.setSpeakerphoneOn(userWantSpeaker);
          } else {
            // route audio to earpiece
            audioManager.setSpeakerphoneOn(userWantSpeaker);
            audioManager.setMode(AudioManager.MODE_NORMAL);
          }
        } else {
          // Non-Samsung and Samsung 2.2 and up devices
          audioManager.setSpeakerphoneOn(userWantSpeaker);
        }
      }
    }

    // Set stream solo/volume/focus

    int inCallStream = Compatibility.getInCallStream(userWantBluetooth);
    if (doFocusAudio) {
      if (!accessibilityManager.isEnabled()) {
        audioManager.setStreamSolo(inCallStream, true);
      }
      audioFocusWrapper.focus(userWantBluetooth);
    }
    Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel());
    setStreamVolume(
        inCallStream,
        (int)
            (audioManager.getStreamMaxVolume(inCallStream)
                * service.getPrefs().getInitialVolumeLevel()),
        0);

    isSetAudioMode = true;
    // System.gc();
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_watch);
    ButterKnife.bind(this);

    getWindow()
        .addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 保持屏幕常亮
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD // 关闭键盘
            );

    // 退出登录并使用username_uuid登录,记着拼接下划线(LoginUtil.USERNAME_EYE_DEPART)
    LoginUtil.relogin(
        AppConfig.getUsername() + LoginUtil.USERNAME_EYE_DEPART + CommonUtil.getUUID(this),
        new EMCallBack() {
          @Override
          public void onSuccess() {
            LogUtil.e("xmh-login", "eye");
            initAfterLogin();
          }

          @Override
          public void onError(int i, String s) {
            // do nothing
          }

          @Override
          public void onProgress(int i, String s) {
            // do nothing
          }
        });

    callHelper = EMVideoCallHelper.getInstance();
    LogUtil.e("xmh-record", "helper-create");
    cameraHelper = new CameraHelper(this, callHelper, surface.getHolder());

    callHelper.setSurfaceView(null);
    surface.getHolder().addCallback(new LocalCallback());

    // 设置视频状态监听
    setCallStateListener();
    setConnectionListener();
    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_RINGTONE);
    audioManager.setSpeakerphoneOn(true);

    // 监听结束通话广播
    LocalBroadcastManager.getInstance(this)
        .registerReceiver(
            new BroadcastReceiver() {
              @Override
              public void onReceive(Context context, Intent intent) {
                if (isGoing) {
                  // 结束通话
                  EMChatManager.getInstance().endCall();
                  cameraHelper.setStartFlag(false);
                  isGoing = false;
                  LogUtil.e("xmh-record", "end call", true);
                }
              }
            },
            new IntentFilter(CommendUtil.ACTION_END_CALL));
  }
Exemple #25
0
 private void shutdownAudio() {
   AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
   am.setMode(AudioManager.MODE_NORMAL);
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler(this));

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    Point displaySize = new Point();
    getWindowManager().getDefaultDisplay().getRealSize(displaySize);

    vsv = new AppRTCGLView(this, displaySize);
    VideoRendererGui.setView(vsv);
    remoteRender = VideoRendererGui.create(0, 0, 100, 100);
    localRender = VideoRendererGui.create(70, 5, 25, 25);

    vsv.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            toggleHUD();
          }
        });
    setContentView(vsv);
    logAndToast("Tap the screen to toggle stats visibility");

    hudView = new TextView(this);
    hudView.setTextColor(Color.BLACK);
    hudView.setBackgroundColor(Color.WHITE);
    hudView.setAlpha(0.4f);
    hudView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 5);
    hudView.setVisibility(View.INVISIBLE);
    addContentView(hudView, hudLayout);

    if (!factoryStaticInitialized) {
      abortUnless(
          PeerConnectionFactory.initializeAndroidGlobals(this, true, true),
          "Failed to initializeAndroidGlobals");
      factoryStaticInitialized = true;
    }

    AudioManager audioManager = ((AudioManager) getSystemService(AUDIO_SERVICE));
    // TODO(fischman): figure out how to do this Right(tm) and remove the
    // suppression.
    @SuppressWarnings("deprecation")
    boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
    audioManager.setMode(
        isWiredHeadsetOn ? AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);

    sdpMediaConstraints = new MediaConstraints();
    sdpMediaConstraints.mandatory.add(
        new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
    sdpMediaConstraints.mandatory.add(
        new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));

    final Intent intent = getIntent();
    if ("android.intent.action.VIEW".equals(intent.getAction())) {
      connectToRoom(intent.getData().toString());
      return;
    }
    showGetRoomUI();
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mHandler = new Handler();

    mResources = getResources();

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

    mLogTextView = (TextView) findViewById(R.id.LogTextView);

    mSampleRateRadioGroup = (RadioGroup) findViewById(R.id.SampleRateRadioGroup);
    mSampleRateRadioGroup.check(R.id.SampleRateRadioButton_44100);

    mSelectModeRadioGroup = (RadioGroup) findViewById(R.id.SelectModeRadioGroup);
    mSelectModeRadioGroup.check(R.id.SelectModeRadioButton_MIC);

    Button button;

    //////////////////////////////////////////////////////////////
    //
    // MediaPalyer
    //
    //////////////////////////////////////////////////////////////
    mMediaPlayer = MediaPlayer.create(this, R.raw.google_moog_dq_16000hz);

    button = (Button) findViewById(R.id.MediaPlayerPlayButton);
    button.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            if (mMediaPlayer.isPlaying()) {
              mMediaPlayer.stop();
              try {
                mMediaPlayer.prepare();
                mMediaPlayer.seekTo(0);
              } catch (Exception e) {
              }
            }
            mMediaPlayer.start();
          }
        });

    button = (Button) findViewById(R.id.MediaPlayerStopButton);
    button.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            if (mMediaPlayer.isPlaying()) {
              mMediaPlayer.stop();
              try {
                mMediaPlayer.prepare();
                mMediaPlayer.seekTo(0);
              } catch (Exception e) {
              }
            }
          }
        });

    //////////////////////////////////////////////////////////////
    //
    // AudioTrack
    //
    //////////////////////////////////////////////////////////////

    button = (Button) findViewById(R.id.AudioTrackPlayButton);
    button.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            playAudioTrack();
          }
        });

    button = (Button) findViewById(R.id.AudioTrackStopButton);
    button.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            stopAudioTrack();
          }
        });

    button = (Button) findViewById(R.id.SpeakerButton);
    button.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Button b = (Button) v;
            boolean isSpeakerOn = mAudioManager.isSpeakerphoneOn();
            if (mAudioManager != null) {
              mAudioManager.setSpeakerphoneOn(!isSpeakerOn);
              appendLogTextView("setSpeakerphoneOn(" + (!isSpeakerOn ? "true" : "false") + ")\n");
            }
            if (mAudioManager.isSpeakerphoneOn()) {
              b.setText("Speaker OFF");
            } else {
              b.setText("Speaker ON");
            }
          }
        });
    if (mAudioManager.isSpeakerphoneOn()) {
      button.setText("Speaker OFF");
    } else {
      button.setText("Speaker ON");
    }

    if (isAcousticEchoCancelerSupported()) {
      appendLogTextView("AEC is supported.\n");
    } else {
      appendLogTextView("AEC is NOT supported.\n");
    }

    if (mAudioManager.isBluetoothScoOn()) {
      appendLogTextView("Bluetooth SCO is ON.\n");
    } else {
      appendLogTextView("Bluetooth SCO is OFF.\n");
    }

    setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    appendLogTextView("setVolumeControlStream(STREAM_VOICE_CALL)\n");

    mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    appendLogTextView("setMode(MODE_IN_COMMUNICATION)\n");
  }
  public void start(ClientOptions opt, Context context) {

    if (showing) stop();
    synchronized (this) {
      codec.init();
      mu = codec.samp_rate() / 8000;
      maxjitter =
          AudioTrack.getMinBufferSize(
              codec.samp_rate(), AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
      if (maxjitter < 2 * 2 * BUFFER_SIZE * 3 * mu) maxjitter = 2 * 2 * BUFFER_SIZE * 3 * mu;
      audioTrack =
          new AudioTrack(
              AudioManager.STREAM_VOICE_CALL,
              codec.samp_rate(),
              AudioFormat.CHANNEL_OUT_MONO,
              AudioFormat.ENCODING_PCM_16BIT,
              maxjitter,
              AudioTrack.MODE_STREAM);
      AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
      /*if (Integer.parseInt(Build.VERSION.SDK) >= 5)
      	am.setSpeakerphoneOn(true);
      else*/
      am.setMode(AudioManager.MODE_IN_COMMUNICATION);
      audioTrack.play();

      running = true;
    }
    // BigBlueButtonClient bbb = ((BigBlueButton)
    // getContext().getApplicationContext()).getHandler();
    videoReceiver =
        new VideoReceiver(opt) {
          @Override
          protected void onVideo(Video video) {
            // VideoChild vc=new VideoChild(video);
            Log.d("video", "video received");
            byte[] data = video.getBody();
            enqueueFrame(data, data.length);
          }

          @Override
          protected void onAudio(Audio audio) {
            // VideoChild vc=new VideoChild(video);

            byte[] audioData = audio.getByteArray();

            int offset = 1;

            //      byte[] tmpBuffer = new byte[audioData.length - offset];
            //      System.arraycopy(audioData, offset, tmpBuffer, 0, tmpBuffer.length);
            //      pkt.setPayload(tmpBuffer, tmpBuffer.length);
            //      int decodedSize = codec.decode(pktBuffer, decodedBuffer,
            // pkt.getPayloadLength());

            System.arraycopy(audioData, offset, pktBuffer, 12, audioData.length - offset);
            int decodedSize = codec.decode(pktBuffer, decodedBuffer, audioData.length - offset);
            write(decodedBuffer, 0, decodedSize);
          }
        };

    // float tmp = videoReceiver.getAspectRatio();
    aspectRatio = DEFAULT_ASPECT_RATIO;

    updateLayoutParams(inDialog);

    videoReceiver.start();

    showing = true;
  }