当前位置:网站首页>音频焦点系列:手写一个demo理解音频焦点与AudioMananger
音频焦点系列:手写一个demo理解音频焦点与AudioMananger
2022-07-03 05:03:00 【zhangjin1120】
先看测试效果:
- 先打开demo,点击“start”等一会儿(本地音频加载需要时间),赛车声音会循环播放。
- home键回到桌面,找到酷狗音乐APP并打开,播放一首歌曲,这时logcat里面会打印
AUDIOFOCUS_LOSS,Demo App会暂停播放。 - 手动暂停酷狗音乐播放器(log不会有变化,也就是并没有触发
AUDIOFOCUS_GAIN)。 - 设置闹钟,闹钟触发,log显示
AUDIOFOCUS_LOSS_TRANSIENT - 关闭闹钟,log显示
AUDIOFOCUS_GAIN
![]() ![]() |
Demo源码
布局文件就一个按钮,自己写布局哈,完整Demo代码如下,注释写的很清楚了,就不解释了。
public class MainActivity extends AppCompatActivity {
private final String TAG = "xxx";
private AudioManager mAudioManager;
private MediaPlayer mMediaPlayer;
private Button btmMusic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
private void initData() {
//初始化AudioManager对象
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//申请焦点
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
AssetFileDescriptor fileDescriptor;
try {
//获取音频文件
fileDescriptor = this.getAssets().openFd("11582.mp3");
//实例化MediaPlayer对象
mMediaPlayer = new MediaPlayer();
//设置播放流类型
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//设置播放源,有多个参数可以选择,具体参考相关文档,本文旨在介绍音频焦点
mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
//设置循环播放
mMediaPlayer.setLooping(true);
//准备监听
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
//准备完成后自动播放
mMediaPlayer.start();
}
});
//异步准备
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initView() {
btmMusic = (Button) findViewById(R.id.btm_music);
if (btmMusic != null) {
btmMusic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
stop();
} else {
start();
}
}
}
});
}
}
private void start() {
btmMusic.setText("Stop");
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mMediaPlayer.start();
}
private void stop() {
btmMusic.setText("Start");
mMediaPlayer.pause();
}
/** * 焦点变化监听器 */
private AudioManager.OnAudioFocusChangeListener mAudioFocusChange = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
//长时间丢失焦点
Log.d(TAG, "AUDIOFOCUS_LOSS");
stop();
//释放焦点
mAudioManager.abandonAudioFocus(mAudioFocusChange);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
//短暂性丢失焦点
stop();
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
//短暂性丢失焦点并作降音处理
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
case AudioManager.AUDIOFOCUS_GAIN:
//重新获得焦点
Log.d(TAG, "AUDIOFOCUS_GAIN");
start();
break;
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.release();
mAudioManager.abandonAudioFocus(mAudioFocusChange);
}
}
音频焦点的实用场景有哪些?
- 打开酷狗音乐播放一首歌曲,再打开B站,播放视频,这时酷狗会自动暂停,按返回键退出视频播放时,酷狗又会自动恢复播放音乐。
官网怎么描述音频焦点的?
边栏推荐
- 雇佣收银员(差分约束)
- [set theory] relation properties (transitivity | transitivity examples | transitivity related theorems)
- Market status and development prospects of the global autonomous marine glider industry in 2022
- Caijing 365 stock internal reference: what's the mystery behind the good father-in-law paying back 50 million?
- Wechat applet waterfall flow and pull up to the bottom
- 2022-02-11 daily clock in: problem fine brush
- Notes | numpy-08 Advanced index
- 并发操作-内存交互操作
- MediaTek 2023 IC written examination approved in advance (topic)
- The 19th Zhejiang I. barbecue
猜你喜欢

Coordinatorlayout appbarrayout recyclerview item exposure buried point misalignment analysis
![[research materials] 2021 annual report on mergers and acquisitions in the property management industry - Download attached](/img/95/833f5ec20207ee5d7e6cdfa7208c5e.jpg)
[research materials] 2021 annual report on mergers and acquisitions in the property management industry - Download attached

Analysis of proxy usage of ES6 new feature

ZABBIX monitoring of lamp architecture (3): zabbix+mysql (to be continued)

Concurrent operation memory interaction

Three representations of signed numbers: original code, inverse code and complement code

论文阅读_清华ERNIE

leetcode860. Lemonade change

Class loading mechanism (detailed explanation of the whole process)

Basic knowledge of reflection (detailed explanation)
随机推荐
[Yu Yue education] basic reference materials of interchangeability and measurement technology of Zhongyuan Institute of Technology
[develop wechat applet local storage with uni app]
第十九届浙江省 I. Barbecue
[tools run SQL blind note]
cookie session jwt
Market status and development prospect prediction of the near infrared sensor industry of the global Internet of things in 2022
Keepalived热备与HAProxy
Unity tool Luban learning notes 1
The 19th Zhejiang I. barbecue
Market status and development prospect prediction of global fermentation acid industry in 2022
The consumption of Internet of things users is only 76 cents, and the price has become the biggest obstacle to the promotion of 5g industrial interconnection
What is UUID
"Pthread.h" not found problem encountered in compiling GCC
文献阅读_基于多模态数据语义融合的旅游在线评论有用性识别研究(中文文献)
C language self-made Games: Sanzi (tic tac toe chess) intelligent chess supplement
Dynamic programming - related concepts, (tower problem)
2022-02-12 daily clock in: problem fine brush
Market status and development prospect prediction of global neutral silicone sealant industry in 2022
Market status and development prospects of the global IOT active infrared sensor industry in 2022
On typescript and grammar

