cstriker1407的笔记本

好记性不如铅笔头

android, 编程

Android应用开发笔记:AudioFocus的使用

当我们在开发Android的音频类应用程序时,往往会设计到音频硬件资源的抢占,比如用户打开音乐播放软件播放音乐等。这时,我们通过注册AudioFocus来实现音频的管理。这里简单的备份下代码:

public int requestAudioFocus(Context _context)
 {
  AudioManager am = (AudioManager) _context.getSystemService(Context.AUDIO_SERVICE);
  // Request audio focus for playback
  int result = am.requestAudioFocus(afChangeListener,
                                   // Use the music stream.
                                   AudioManager.STREAM_VOICE_CALL,
                                   // Request permanent focus.
                                   AudioManager.AUDIOFOCUS_GAIN);
     
  if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
  }
  return 0;
 }
 public int abandonAudioFocus(Context _context)
 {
  AudioManager am = (AudioManager) _context.getSystemService(Context.AUDIO_SERVICE);
  am.abandonAudioFocus(afChangeListener);
  return 0;
 }
 
 private OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() 
 {
     public void onAudioFocusChange(int focusChange) 
     {
         if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
         {
          Log.e(tag, "lose focus shortly");        
         } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) 
         {
          Log.e(tag, "gain focus");
         } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) 
         {
          Log.e(tag, "lose focus");
         }
     }
 };

 

Leave a Reply

20 − 17 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Theme by Anders Norén

苏ICP备16032087号