当前位置:网站首页>音频焦点系列:手写一个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站,播放视频,这时酷狗会自动暂停,按返回键退出视频播放时,酷狗又会自动恢复播放音乐。
官网怎么描述音频焦点的?
边栏推荐
- 动态规划——相关概念,(数塔问题)
- MediaTek 2023 IC written examination approved in advance (topic)
- Thesis reading_ Chinese NLP_ ELECTRA
- Review the configuration of vscode to develop golang
- 1106 lowest price in supply chain (25 points)
- Without 50W bride price, my girlfriend was forcibly dragged away. What should I do
- Thesis reading_ Chinese medical model_ eHealth
- I stepped on a foundation pit today
- On typescript and grammar
- Uipath practice (08) - selector
猜你喜欢

Learn to use the idea breakpoint debugging tool

Interface frequency limit access

Esp32-c3 learning and testing WiFi (II. Wi Fi distribution - smart_config mode and BlueIf mode)

Source insight garbled code solution

"Hands on deep learning" pytorch edition Chapter II exercise

First + only! Alibaba cloud's real-time computing version of Flink passed the stability test of big data products of the Institute of ICT

String matching: find a substring in a string

Promise
![[XSS bypass - protection strategy] understand the protection strategy and better bypass](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[XSS bypass - protection strategy] understand the protection strategy and better bypass

Use Sqlalchemy module to obtain the table name and field name of the existing table in the database
随机推荐
Shell script -- condition judgment
Notes | numpy-11 Array operation
[backtrader source code analysis 5] rewrite several time number conversion functions in utils with Python
并发操作-内存交互操作
sql语句模糊查询遇到的问题
Actual combat 8051 drives 8-bit nixie tube
Preparation for school and professional cognition
Source insight garbled code solution
[tools run SQL blind note]
M1 Pro install redis
Silent authorization login and registration of wechat applet
论文阅读_ICD编码_MSMN
Market status and development prospects of the global autonomous marine glider industry in 2022
[research materials] 2021 annual report on mergers and acquisitions in the property management industry - Download attached
Unity tool Luban learning notes 1
MySQL master-slave configuration
Thesis reading_ Chinese medical model_ eHealth
Huawei personally ended up developing 5g RF chips, breaking the monopoly of Japan and the United States
第十九届浙江省 I. Barbecue
Learn to use the idea breakpoint debugging tool

