解决部分华为,乐视手机听筒模式听不到声音问题

最近项目中出现一个问题,部分华为手机,乐视手机切换到听筒模式后,听不到声音的现象,搜索了好多答案,发现都是说设置模式不对,试了好多也没有解决掉。最后发现应该是重新播放的方式不对,在一部分手机上重新播放不兼容。

这是开始的代码,切换到听筒模式时调用:

VoicePlayer.setAudioManagerMode(AudioManager.MODE_IN_CALL);
((ChatActivity)context).setSpeakerphoneOn(false);
VoicePlayer.player.seekTo(0);//重新播放

public void setSpeakerphoneOn(boolean on) {
    try {
        AudioManager audioManager = (AudioManager) AndroidUtils.appCtx().getSystemService(Context.AUDIO_SERVICE);
        //播放音频流类型
        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
        //获得当前类
        Class audioSystemClass = Class.forName("android.media.AudioSystem");
        //得到这个方法
        Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);

        if (on) {
            audioManager.setMicrophoneMute(false);
            audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.MODE_NORMAL);
        } else {
		audioManager.setSpeakerphoneOn(false);
 		audioManager.setMode(AudioManager.MODE_NORMAL);
 		setForceUse.invoke(null, 0, 0);
 		audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
} } catch (Exception e) { e.printStackTrace(); }}
这是后来改进的代码 ,切换到听筒模式时调用

VoicePlayer.rePlay(context,mAudioManager,false);

public class VoicePlayer {

   public static interface OnPlayListener extends OnCompletionListener {
      public String getPublicId();

      public void onCancel();

      public void onDownloadBegin();

      public void onDownloadEnd();

      public void onError();
      
      public void onPlayBegin(MediaPlayer player);
      
      public void onReplay();
      
      public void setRecMessageItem(RecMessageItem item);
   }
   /**
    * 管理其他音乐播放器
    * **/
   public interface OtherPlayerManagerI{
      /**
       * 暂停其他播放器
       * **/
      public void pauseOtherPlayer();
      /**
       * 恢复其他播放器
       * **/
      public void replyOtherPlayer();
      /**
       * 释放资源
       * **/
      public void releaseResource();
   }
   /**
    * 播放语音,管理音频焦点
    * **/
   public static  class  OtherPlayerManagerImpl implements OtherPlayerManagerI{
         public static Context otcontext=null;
          public static AudioManager    am=null;
         public  static OtherPlayerManagerImpl playerManagerImpl=null;
         //单例返回
         public  static OtherPlayerManagerImpl getInstance(Context context){       
            OtherPlayerManagerImpl.otcontext = context;
            if(playerManagerImpl==null){
               playerManagerImpl=new OtherPlayerManagerImpl();
            }
            if(am==null){
               am = (AudioManager)otcontext.getSystemService(Context.AUDIO_SERVICE);
            }         
            return playerManagerImpl;
         }
      @Override 
      public void pauseOtherPlayer() {
         int result = am.requestAudioFocus(null,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
      }
      @Override
      public void replyOtherPlayer() {         
         am.abandonAudioFocus(null);    
      }
      @Override
      public void releaseResource() {
         context=null;
         am=null;
         playerManagerImpl=null;
      }  
   }
    public static Context context;
   public static MediaPlayer player;
   public static RecMessageItem curPlayMessage;
   public static OnPlayListener curOnPlayListener;
   private static Set<String> downloading = Collections.synchronizedSet(new HashSet<String>());

   public static int audioManagerMode = AudioManager.MODE_NORMAL;
   
   public static void setAudioManagerMode(int mode){
      audioManagerMode = mode;
   }
   
   public static int getAudioManagerMode(){
      return audioManagerMode;
   }
   
   public static void clear() {
      player = null;
      curPlayMessage = null;
   }
   public static void rePlay(Activity act, AudioManager audioManager, boolean isSpeakerphoneOn) {
      player.stop();
      if (isSpeakerphoneOn) {
         setAudioManagerMode(AudioManager.MODE_NORMAL);
         act.setVolumeControlStream(AudioManager.STREAM_MUSIC);
         audioManager.setMode(AudioManager.MODE_NORMAL);// 切换到外放模式, 继续播放
         audioManager.setSpeakerphoneOn(isSpeakerphoneOn);
      } else {
         setAudioManagerMode(AudioManager.MODE_IN_CALL);
         act.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
         audioManager.setMode(AudioManager.MODE_IN_CALL);//切换到听筒模式
         if (Build.VERSION.SDK_INT >= 11) {
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);//
         }
         audioManager.setSpeakerphoneOn(isSpeakerphoneOn);
      }
      player.release();
      player = null;
      doPlay(curPlayMessage, curOnPlayListener);
   }
   private static boolean doPlay(final RecMessageItem item, final OnPlayListener onPlayListener) {
      // 停掉前一个播放器
      if (player != null) {
         RecMessageItem cpmsg = curPlayMessage;
         try {
            player.release();
            curOnPlayListener.onCancel();
            SystemClock.sleep(300);
         } catch (Exception e) {
            // ignore...
         } finally {
            player = null;
            curOnPlayListener = null;
         }
         if (cpmsg != null && cpmsg.equals(item)) {
            return true;
         }
      }
      
      curPlayMessage = item;
      curOnPlayListener = onPlayListener;
      
      curOnPlayListener.setRecMessageItem(item);
      
      File encryptedFile = new File(MessageUtils.genMsgFileName(item.msgId));

      // 播放的文件已经缓存在本地,则直接播放
      if (encryptedFile.exists()) {
         FileInputStream voiceIS = null;
         File voiceFile = null;
         try {
            // decrypt it first...
            FileOutputStream voiceOS = AndroidUtils.appCtx().openFileOutput("voice", Context.MODE_PRIVATE);
            MessageUtils.deCrypt(new FileInputStream(encryptedFile), voiceOS);
            voiceFile = AndroidUtils.appCtx().getFileStreamPath("voice");
            voiceIS = new FileInputStream(voiceFile);

            // then play it
            player = new MediaPlayer();
            player.setDataSource(voiceIS.getFD());
            player.prepare();
            player.setOnCompletionListener(curOnPlayListener);
            player.start();
            curOnPlayListener.onPlayBegin(player);
            Log.e("AudioManager", "" + VoicePlayer.audioManagerMode);
            AudioManager audioManager = (AudioManager) AndroidUtils.appCtx().getSystemService(Context.AUDIO_SERVICE);
            if(VoicePlayer.audioManagerMode == AudioManager.MODE_NORMAL){
               audioManager.setMode(AudioManager.MODE_NORMAL);// 切换到外放模式, 继续播放
               audioManager.setSpeakerphoneOn(true);
            }else if (VoicePlayer.audioManagerMode == AudioManager.MODE_IN_CALL) {
               audioManager.setMode(AudioManager.MODE_IN_CALL);// //切换到听筒模式
               audioManager.setSpeakerphoneOn(false);
            }
         } catch (Exception e) {
            LogUtil.i("VoicePlayer", e.getMessage(), e);
            encryptedFile.delete();
            curOnPlayListener.onError();
            return false;
         } finally {
            if (voiceIS != null) {
               try {
                  voiceIS.close();
               } catch (Exception e) {
               }
            }
            if (voiceFile != null)
               voiceFile.delete();
         }

         return true;
      } else if (downloading.contains(item.msgId)) {
         return true;
      }

      return false;
   }

   private static void downloadAndPlay(final RecMessageItem item, final OnPlayListener onPlayListener) {
      if (!downloading.add(item.msgId)) {
         return;
      }

      onPlayListener.onDownloadBegin();

      new AsyncTask<String, Integer, Boolean>() {

         @Override
         protected Boolean doInBackground(String... params) {

            try {
               MessageUtils.getFileFromServer(onPlayListener.getPublicId(),item.groupId, item.msgId);
            } catch (Exception e) {
               e.printStackTrace();
               return false;

            }
            return true;
         };

         protected void onPostExecute(Boolean result) {
            onPlayListener.onDownloadEnd();
            downloading.remove(item.msgId);
            if (!result) {
               AndroidUtils.toastShort("无法下载当前音频");
               onPlayListener.onError();
               return;
            }

            if (curPlayMessage == null || curPlayMessage.msgId.equals(item.msgId)) {
               doPlay(item, onPlayListener);
            }

         }

      }.execute("");

   }

   public static void onDestroy() {
      // 停掉前一个播放器
      if (player != null) {
         player.release();
         if (curOnPlayListener != null)
            curOnPlayListener.onCancel();
         player = null;
         curPlayMessage = null;
      }
   }

   public static void play(final RecMessageItem item, final OnPlayListener onPlayListener,Context context) {
      VoicePlayer.context=context;
      if (item == null)
         return;
      if (doPlay(item, onPlayListener)) {
         return;
      }

      // 文件还未下载,则直接下载之后再播放
      downloadAndPlay(item, onPlayListener);

   }

}
希望我的经历对你有所帮助,欢迎大家评论交流!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值