我是靠谱客的博主 畅快野狼,最近开发中收集的这篇文章主要介绍android使用MediaPlayer加AudioManager 封装播放音乐,外加切换蓝牙,耳机,内放,外放,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

项目需要 写了个音乐播放器,要适配本地声音和网络获取的声音,而且切换评率非常高,而且老板总喜欢带蓝牙耳机,所以输出音频要根据设备关联 我这边给大家提供一个简单的工具 

public class BgmPlayer {
private final MediaPlayer mMediaPlayer;
private
AudioManager mAudioManager;
private final BluetoothAdapter ba;
private boolean mPlay;
private boolean mPause;
private boolean LooPing = true;
private Context context;
private final AudioManager.OnAudioFocusChangeListener mFocusChangeListener;
public BgmPlayer(Context context) {
this.context = context;
mMediaPlayer = new MediaPlayer();
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//
if (mAudioManager.isWiredHeadsetOn()) {
//
changeToHeadset();
//
//
} else {
//
changeToSpeaker();
//
//
}
ba = BluetoothAdapter.getDefaultAdapter();
if (ba == null) {
//
isBlueCon = -1;
//error
//return -1;
} else if (ba.isEnabled()) {
int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);
//可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET);
//蓝牙头戴式耳机,支持语音输入输出
int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH);
//蓝牙穿戴式设备
//查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态
int flag = -1;
if (a2dp == BluetoothProfile.STATE_CONNECTED) {
flag = a2dp;
} else if (headset == BluetoothProfile.STATE_CONNECTED) {
flag = headset;
} else if (health == BluetoothProfile.STATE_CONNECTED) {
flag = health;
}
//说明连接上了三种设备的一种
if (flag != -1) {
//
isBlueCon = 1;
//connected
//
return 2;
changeToSpeaker();//蓝牙
}
}
mFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
pause();
}
}
};
}
/**
* 切换到外放
连接设备
*/
public void changeToSpeaker() {
KLog.e("tag", "切换到外放");
mAudioManager.setMode(AudioManager.MODE_NORMAL);
mAudioManager.setSpeakerphoneOn(true);
}
/**
* 切换到耳机模式
*/
public void changeToHeadset() {
KLog.e("tag", "切换到内放");
mAudioManager.setSpeakerphoneOn(false);
}
/**
* 切换到听筒
手机自带喇叭
*/
public void changeToReceiver() {
mAudioManager.setSpeakerphoneOn(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
} else {
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
}
}
public boolean isPlay() {
return mPlay;
}
public boolean isPause() {
return mPause;
}
public void play(String url) {
LooPing = true;
mPlay = false;
LogPlus.e("播放=" + url);
if (TextUtils.isEmpty(url)) {
return;
}
initPlayerAndPlay(url);
}
public void plays(String url, boolean LooPing) {
this.LooPing = LooPing;
mPlay = false;
LogPlus.e("播放=" + url);
if (TextUtils.isEmpty(url)) {
return;
}
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
changeToSpeaker();
initPlayerAndPlay(url);
}
private void initPlayerAndPlay(String url) {
mPause = false;
String md5 = Md5Util.md5(url);
File dstFile = getDstFile(md5);
if (dstFile.exists()) {
playLocal(dstFile);
} else {
downLoad(url, md5, dstFile);
playNet(url);
}
}
private void playLocal(File dstFile) {
try {
KLog.e("TAG", "开始");
mMediaPlayer.setLooping(LooPing);//是否循环播放
mMediaPlayer.setDataSource(dstFile.getAbsolutePath());//通过一个具体的路径来设置MediaPlayer的数据源,path可以是本地的一个路径,也可以是一个网络路径
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare(); //准备播放
mMediaPlayer.start();//开始播放
mPlay = true;
requestPermanentAudioFocus(true, mFocusChangeListener);
} catch (IOException e) {
e.printStackTrace();
mMediaPlayer.reset();
requestPermanentAudioFocus(false, mFocusChangeListener);
}
}
private void playNet(String url) {
try {
mMediaPlayer.setLooping(LooPing);
mMediaPlayer.setDataSource(url);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//手机音乐的声音
mMediaPlayer.prepareAsync(); //异步准备播放
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();//开始播放
mPlay = true;
requestPermanentAudioFocus(true, mFocusChangeListener);
}
});
} catch (IOException e) {
e.printStackTrace();
mMediaPlayer.reset();
requestPermanentAudioFocus(false, mFocusChangeListener);
}
}
public void resume() {
if (mPlay && mPause) {
mMediaPlayer.start();
mPause = false;
requestPermanentAudioFocus(true, mFocusChangeListener);
}
}
public void pause() {
if (mPlay) {
mMediaPlayer.pause();
mPause = true;
requestPermanentAudioFocus(false, mFocusChangeListener);
}
}
public void stop() {
mPlay = false;
mMediaPlayer.pause();
mMediaPlayer.stop();
mMediaPlayer.reset();
requestPermanentAudioFocus(false, mFocusChangeListener);
}
public void release() {
KLog.e("TAG", "退出房间,音频关闭");
mPlay = false;
mMediaPlayer.stop();
mMediaPlayer.release();
requestPermanentAudioFocus(false, mFocusChangeListener);
}
private File getDstFile(String mds) {
File dstDir = FileUtil.getInternalFileDir("bgms");
File dstFile = new File(dstDir, mds + ".bgm");
return dstFile;
}
private void downLoad(String url, String md5, final File dstFile) {
File tempDir = FileUtil.getInternalCacheDir("tmp_bgms");
String tempName = md5 + ".tmp";
File tempFile = new File(tempDir, tempName);
tempFile.delete();
OkGo.<File>get(url).execute(new FileCallback(tempDir.getAbsolutePath(), tempName) {
@Override
public void onSuccess(Response<File> response) {
LogPlus.e("下载完毕");
File body = response.body();
body.renameTo(dstFile);
}
});
}
/**
* 获取永久的音频焦点
*
* @param request
* @return
*/
public boolean requestPermanentAudioFocus(boolean request,
AudioManager.OnAudioFocusChangeListener listener) {
if (request) {
int result = mAudioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
} else {
int result = mAudioManager.abandonAudioFocus(listener);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
}
/**
* 获取短暂的音频焦点
*
* @param request
* @return
*/
public boolean requestTransientAudioFocus(boolean request,
AudioManager.OnAudioFocusChangeListener listener) {
if (request) {
int result = mAudioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
} else {
int result = mAudioManager.abandonAudioFocus(listener);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
}
}

注册代码

mBgmPlayer = new BgmPlayer(mActivityView.getActivity());

使用的时候直接

if (!mBgmPlayer.isPlay()) {
mBgmPlayer.play(url);//循环播放
}
mBgmPlayer.stop();暂停 
mBgmPlayer.release();销毁
mBgmPlayer.plays(url,false);不循环播放

最后

以上就是畅快野狼为你收集整理的android使用MediaPlayer加AudioManager 封装播放音乐,外加切换蓝牙,耳机,内放,外放的全部内容,希望文章能够帮你解决android使用MediaPlayer加AudioManager 封装播放音乐,外加切换蓝牙,耳机,内放,外放所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部