AudioManager获取、释放媒体焦点

转载自:http://blog.csdn.net/chenchuntong/article/details/8813719

平时开发的时候 遇到这样的一个问题: 我开着系统的音乐播放器,我在我的应用程序里面播一段音乐 两个音乐会同时播放通过在stackoverflow查资料后才发行我们得自己音乐需要获取焦点,在我们音乐播完了以后释放掉焦点。这样系统的歌曲会继续播放下面介绍一下步骤

1.获取AudioManager对象

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

2. 注册OnAudioFocusChangeListener监听

 OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
  public void onAudioFocusChange(int focusChange) {
   if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
    if(mediaPlayer.isPlaying()){
     mediaPlayer.pause();
    }
    
   } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
    if(mediaPlayer==null){
     initBeepSound();
    }else if(!mediaPlayer.isPlaying()){
     
     mediaPlayer.start();
     
    }
    // Resume playback
   } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
    if(mediaPlayer.isPlaying()){
     
     mediaPlayer.stop();
    }
    am.abandonAudioFocus(afChangeListener);
    // Stop playback
   }else if(focusChange==AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
    if (mediaPlayer.isPlaying()) {
     mediaPlayer.stop();
    }
    
   }else if(focusChange==AudioManager.AUDIOFOCUS_REQUEST_FAILED){
    if(mediaPlayer.isPlaying()){
     mediaPlayer.stop();
    }
    
   }
  }
 };
3.就是在我们播放音乐的时候为AudioManager添加获取焦点的监听

int result = am.requestAudioFocus(afChangeListener,
    // Use the music stream.
      AudioManager.STREAM_MUSIC, // Request permanent focus.
      AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
     mediaPlayer.start();
     // Start playback. // 开始播放音乐文件
    }

4.在我们不用的时候将焦点释放掉一般我们是在ondestroy()方法中释放

 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
  am.abandonAudioFocus(afChangeListener);

 }

下面介绍一下AudioManager的几个常量

AUDIOFOCUS_REQUEST_GRANTED   永久获取媒体焦点(播放音乐)

AUDIOFOCUS_GAIN_TRANSIENT  暂时获取焦点 适用于短暂的音频

AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK Duck我们应用跟其他应用共用焦点 我们播放的时候其他音频会降低音量

下面奉上代码

[java]  view plain copy print ?
  1. package com.example.mediatest;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.BroadcastReceiver;  
  7. import android.content.ComponentName;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.content.res.AssetFileDescriptor;  
  11. import android.media.AudioManager;  
  12. import android.media.AudioManager.OnAudioFocusChangeListener;  
  13. import android.media.MediaPlayer;  
  14. import android.media.MediaPlayer.OnCompletionListener;  
  15. import android.os.Bundle;  
  16. import android.view.KeyEvent;  
  17. import android.view.Menu;  
  18. import android.view.View;  
  19. import android.view.View.OnClickListener;  
  20. import android.widget.Button;  
  21. import android.widget.Toast;  
  22.   
  23. public class MainActivity extends Activity {  
  24.   
  25.     private Button play;  
  26.     private Button stop;  
  27.     private AudioManager am;  
  28.     @Override  
  29.     protected void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.activity_main);  
  32.         play = (Button) findViewById(R.id.button1);  
  33.         stop = (Button) findViewById(R.id.button2);  
  34.         am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
  35.         initBeepSound();  
  36.         mode = am.getMode();  
  37.         if (mode == AudioManager.MODE_NORMAL) {  
  38.             Toast.makeText(this"MODE_NORMAL", Toast.LENGTH_LONG).show();  
  39.         } else if (mode == AudioManager.MODE_IN_CALL) {  
  40.             Toast.makeText(this"MODE_IN_CALL", Toast.LENGTH_LONG).show();  
  41.   
  42.         } else if (mode == AudioManager.MODE_RINGTONE) {  
  43.             Toast.makeText(this"MODE_RINGTONE", Toast.LENGTH_LONG).show();  
  44.   
  45.         }  
  46.         remoteControlReceiver = new ComponentName(" com.example.mediatest",  
  47.                 " com.example.mediatest.RemoteControlReceiver");  
  48.         play.setOnClickListener(new OnClickListener() {  
  49.   
  50.             @Override  
  51.             public void onClick(View v) {  
  52.                 if (mediaPlayer != null) {  
  53.                     mediaPlayer.start();  
  54.   
  55.                 } else {  
  56.                     initBeepSound();  
  57.                     mediaPlayer.start();  
  58.                 }  
  59.                 // Request audio focus for playback  
  60.                 int result = am.requestAudioFocus(afChangeListener,  
  61.                 // Use the music stream.  
  62.                         AudioManager.STREAM_MUSIC, // Request permanent focus.  
  63.                         AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);  
  64.                 if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {  
  65.                     mediaPlayer.start();  
  66.                     // Start playback. // 开始播放音乐文件  
  67.                 }  
  68.             }  
  69.   
  70.         });  
  71.         stop.setOnClickListener(new OnClickListener() {  
  72.   
  73.             @Override  
  74.             public void onClick(View v) {  
  75.                 if (mediaPlayer != null && mediaPlayer.isPlaying()) {  
  76.                     mediaPlayer.stop();  
  77.                     mediaPlayer.release();  
  78.                     mediaPlayer = null;  
  79.                 }  
  80.                 am.abandonAudioFocus(afChangeListener);  
  81.             }  
  82.         });  
  83.     }  
  84.   
  85.     OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {  
  86.         public void onAudioFocusChange(int focusChange) {  
  87.             if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {  
  88.                 if (mediaPlayer.isPlaying()) {  
  89.                     mediaPlayer.pause();  
  90.                 }  
  91.   
  92.             } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {  
  93.                 if (mediaPlayer == null) {  
  94.                     initBeepSound();  
  95.                 } else if (!mediaPlayer.isPlaying()) {  
  96.   
  97.                     mediaPlayer.start();  
  98.   
  99.                 }  
  100.                 // Resume playback  
  101.             } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {  
  102.                 if (mediaPlayer.isPlaying()) {  
  103.   
  104.                     mediaPlayer.stop();  
  105.                 }  
  106.                 am.abandonAudioFocus(afChangeListener);  
  107.                 // Stop playback  
  108.             } else if (focusChange == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {  
  109.                 if (mediaPlayer.isPlaying()) {  
  110.                     mediaPlayer.stop();  
  111.                 }  
  112.   
  113.             } else if (focusChange == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {  
  114.                 if (mediaPlayer.isPlaying()) {  
  115.                     mediaPlayer.stop();  
  116.                 }  
  117.   
  118.             }  
  119.         }  
  120.     };  
  121.     /** 
  122.      * When the beep has finished playing, rewind to queue up another one. 
  123.      */  
  124.     private final OnCompletionListener beepListener = new OnCompletionListener() {  
  125.         public void onCompletion(MediaPlayer mediaPlayer) {  
  126.             mediaPlayer.seekTo(0);  
  127.         }  
  128.     };  
  129.     private MediaPlayer mediaPlayer;  
  130.     private ComponentName remoteControlReceiver;  
  131.     private int mode;  
  132.   
  133.     private void initBeepSound() {  
  134.         if (mediaPlayer == null) {  
  135.             // The volume on STREAM_SYSTEM is not adjustable, and users found it  
  136.             // too loud,  
  137.             // so we now play on the music stream.  
  138.             setVolumeControlStream(AudioManager.STREAM_MUSIC);  
  139.             mediaPlayer = new MediaPlayer();  
  140.             mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);  
  141.             mediaPlayer.setOnCompletionListener(beepListener);  
  142.   
  143.             AssetFileDescriptor file = getResources().openRawResourceFd(  
  144.                     R.raw.demo);  
  145.             try {  
  146.                 mediaPlayer.setDataSource(file.getFileDescriptor(),  
  147.                         file.getStartOffset(), file.getLength());  
  148.                 file.close();  
  149.                 mediaPlayer.prepare();  
  150.             } catch (IOException e) {  
  151.                 mediaPlayer = null;  
  152.             }  
  153.         }  
  154.     }  
  155.   
  156.     @Override  
  157.     protected void onStop() {  
  158.         // TODO Auto-generated method stub  
  159.         super.onStop();  
  160.         am.abandonAudioFocus(afChangeListener);  
  161.   
  162.     }  
  163.   
  164.     @Override  
  165.     public boolean onCreateOptionsMenu(Menu menu) {  
  166.         // Inflate the menu; this adds items to the action bar if it is present.  
  167.         getMenuInflater().inflate(R.menu.main, menu);  
  168.         return true;  
  169.     }  
  170.   
  171. }  

你可能感兴趣的:(Android)