1 page.title=Dealing with Audio Output Hardware 2 parent.title=Managing Audio Playback 3 parent.link=index.html 4 5 trainingnavtop=true 6 previous.title=Managing Audio Focus 7 previous.link=audio-focus.html 8 9 @jd:body 10 11 12 <div id="tb-wrapper"> 13 <div id="tb"> 14 15 <h2>This lesson teaches you to</h2> 16 <ol> 17 <li><a href="#CheckHardware">Check What Hardware is Being Used</a></li> 18 <li><a href="#HandleChanges">Handle Changes in the Audio Output Hardware</a></li> 19 </ol> 20 21 22 <h2>You should also read</h2> 23 <ul> 24 <li><a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a></li> 25 </ul> 26 27 28 </div> 29 </div> 30 31 <p>Users have a number of alternatives when it comes to enjoying the audio from their Android 32 devices. Most devices have a built-in speaker, headphone jacks for wired headsets, and many also 33 feature Bluetooth connectivity and support for A2DP audio. </p> 34 35 36 <h2 id="CheckHardware">Check What Hardware is Being Used</h2> 37 38 <p>How your app behaves might be affected by which hardware its output is being routed to.</p> 39 40 <p>You can query the {@link android.media.AudioManager} to determine if the audio is currently 41 being routed to the device speaker, wired headset, or attached Bluetooth device as shown in the 42 following snippet:</p> 43 44 <pre> 45 if (isBluetoothA2dpOn()) { 46 // Adjust output for Bluetooth. 47 } else if (isSpeakerphoneOn()) { 48 // Adjust output for Speakerphone. 49 } else if (isWiredHeadsetOn()) { 50 // Adjust output for headsets 51 } else { 52 // If audio plays and noone can hear it, is it still playing? 53 } 54 </pre> 55 56 57 <h2 id="HandleChanges">Handle Changes in the Audio Output Hardware</h2> 58 59 <p>When a headset is unplugged, or a Bluetooth device disconnected, the audio stream 60 automatically reroutes to the built in speaker. If you listen to your music at as high a volume as I 61 do, that can be a noisy surprise.</p> 62 63 <p>Luckily the system broadcasts an {@link android.media.AudioManager#ACTION_AUDIO_BECOMING_NOISY} 64 intent when this happens. Its good practice to register a {@link android.content.BroadcastReceiver} 65 that listens for this intent whenever youre playing audio. In the case of music players, users 66 typically expect the playback to be paused—while for games you may choose to significantly 67 lower the volume.</p> 68 69 <pre> 70 private class NoisyAudioStreamReceiver extends BroadcastReceiver { 71 @Override 72 public void onReceive(Context context, Intent intent) { 73 if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) { 74 // Pause the playback 75 } 76 } 77 } 78 79 private IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); 80 81 private void startPlayback() { 82 registerReceiver(myNoisyAudioStreamReceiver(), intentFilter); 83 } 84 85 private void stopPlayback() { 86 unregisterReceiver(myNoisyAudioStreamReceiver); 87 } 88 </pre> 89