2015-10-30 99 views
0

我正在尋找一種方法來播放來自Android設備揚聲器的音頻,即使插入了耳機。Android,耳機插入時如何將音頻路由至揚聲器?

實際上,典型的行爲是,當插入耳機時,沒有音頻從揚聲器輸出。然而,即使插入耳機,某些應用程序(如默認的時鐘應用程序(com.google.android.deskclock))也能夠將音頻路由至揚聲器。

如何以編程方式獲得此行爲?

我要找Nexus 5的設備是有效的解決方案(至少),運行奇巧(安卓4.4)

感謝。

回答

2

大概在這個應用程序的源代碼看看會有所幫助。我找到了一個可以完成這項工作的AsyncRingtonePlayer類(https://android.googlesource.com/platform/packages/apps/DeskClock/+/master/src/com/android/deskclock/AsyncRingtonePlayer.java)。

訣竅是使用不同的Audiostream,我猜。讓我們來看一看一個的startAlarm法:

private void startAlarm(MediaPlayer player) throws IOException { 
     // do not play alarms if stream volume is 0 (typically because ringer mode is silent). 
     if (mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { 
      if (Utils.isLOrLater()) { 
       player.setAudioAttributes(new AudioAttributes.Builder() 
         .setUsage(AudioAttributes.USAGE_ALARM) 
         .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 
         .build()); 
      } 
      player.setAudioStreamType(AudioManager.STREAM_ALARM); 
      player.setLooping(true); 
      player.prepare(); 
      mAudioManager.requestAudioFocus(null, AudioManager.STREAM_ALARM, 
        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); 
      player.start(); 
     } 
    } 

選手對象的音頻流類型將被設置爲AudioManager.STREAM_ALARM。我想這可能是解決方案。我沒有測試它,但這是我在源代碼中發現的第一件事。

請也意識到作爲AndroidManifest列出了一些必要的權限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
<uses-permission android:name="android.permission.WAKE_LOCK"/> 
<uses-permission android:name="android.permission.VIBRATE"/> 
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> 
<!-- WRITE_SETTINGS is required to record the upcoming alarm prior to L --> 
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> 
<!-- READ_PHONE_STATE is required to determine when a phone call exists prior to M --> 
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
<!-- READ_EXTERNAL_STORAGE is required to play custom ringtones from the SD card prior to M --> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

https://android.googlesource.com/platform/packages/apps/DeskClock/+/master/AndroidManifest.xml

+0

此代碼工作代碼! 在下面發表我的最終解決方案... – user975176

0

刪除不需要的是Android 4.4

//context = a valid context 
AudioManager am = (AudioManager) context.getSystemService(context.AUDIO_SERVICE); 
MediaPlayer mp = new MediaPlayer(); 
Uri loc = Uri.parse("android.resource://com.example.test/" + R.raw.music); 
try { 
    mp.setDataSource(context, loc); 
    mp.setAudioStreamType(AudioManager.STREAM_ALARM); 
    mp.setLooping(true); 
    mp.prepare(); 
} catch (IllegalArgumentException | SecurityException| IllegalStateException | IOException e) { 
    e.printStackTrace(); 
} 
am.requestAudioFocus(null, AudioManager.STREAM_ALARM,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); 
mp.start(); 
相關問題