Android AudioManager获取媒体焦点(精华)

Android AudioManager获取媒体焦点

分类: Android 557人阅读 评论(1) 收藏 举报

      平时开发的时候 遇到这样的一个问题: 我开着系统的音乐播放器,我在我的应用程序里面播一段音乐 两个音乐会同时播放通过在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我们应用跟其他应用共用焦点 我们播放的时候其他音频会降低音量

下面奉上代码:

package com.example.mediatest;

import java.io.IOException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button play;
    private Button stop;
    private AudioManager am;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = (Button) findViewById(R.id.button1);
        stop = (Button) findViewById(R.id.button2);
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        initBeepSound();
        mode = am.getMode();
        if (mode == AudioManager.MODE_NORMAL) {
            Toast.makeText(this, "MODE_NORMAL", Toast.LENGTH_LONG).show();
        } else if (mode == AudioManager.MODE_IN_CALL) {
            Toast.makeText(this, "MODE_IN_CALL", Toast.LENGTH_LONG).show();

        } else if (mode == AudioManager.MODE_RINGTONE) {
            Toast.makeText(this, "MODE_RINGTONE", Toast.LENGTH_LONG).show();

        }
        remoteControlReceiver = new ComponentName(" com.example.mediatest",
                " com.example.mediatest.RemoteControlReceiver");
        play.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    mediaPlayer.start();

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

        });
        stop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                am.abandonAudioFocus(afChangeListener);
            }
        });
    }

    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();
                }

            }
        }
    };
    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
    private MediaPlayer mediaPlayer;
    private ComponentName remoteControlReceiver;
    private int mode;

    private void initBeepSound() {
        if (mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.demo);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

 

linker : http://blog.csdn.net/chenchuntong/article/details/8813719

 

你可能感兴趣的:(Android AudioManager获取媒体焦点(精华))