当前位置:网站首页>音频焦点系列:手写一个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站,播放视频,这时酷狗会自动暂停,按返回键退出视频播放时,酷狗又会自动恢复播放音乐。
官网怎么描述音频焦点的?
边栏推荐
- Thesis reading_ Chinese NLP_ ELECTRA
- Market status and development prospect forecast of global button dropper industry in 2022
- [backtrader source code analysis 4] use Python to rewrite the first function of backtrader: time2num, which improves the efficiency by 2.2 times
- Market status and development prospect prediction of the global fire alarm sensor industry in 2022
- 编译GCC遇到的“pthread.h” not found问题
- Learning record of arouter principle
- Market status and development prospect prediction of the global autonomous hybrid underwater glider industry in 2022
- JQ style, element operation, effect, filtering method and transformation, event object
- Dynamic programming - related concepts, (tower problem)
- Notes | numpy-09 Broadcast
猜你喜欢

MPM model and ab pressure test

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

Handling record of electric skateboard detained by traffic police

Handler understands the record

论文阅读_中文NLP_ELECTRA

Flutter monitors volume to realize waveform visualization of audio

The programmer resigned and was sentenced to 10 months for deleting the code. JD came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
![[luatos sensor] 2 air pressure bmp180](/img/88/2a6caa5fec95e54e3fb09c74ba8ae6.jpg)
[luatos sensor] 2 air pressure bmp180

Cross platform plug-in flutter for displaying local notifications_ local_ notifications

5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip
随机推荐
Literature reading_ Research on the usefulness identification of tourism online comments based on semantic fusion of multimodal data (Chinese Literature)
Learning record of arouter principle
1095 cars on campus (30 points)
[develop wechat applet local storage with uni app]
文献阅读_基于多模态数据语义融合的旅游在线评论有用性识别研究(中文文献)
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
[set theory] relational representation (relational matrix | examples of relational matrix | properties of relational matrix | operations of relational matrix | relational graph | examples of relationa
Compile and decompile GCC common instructions
Wechat applet waterfall flow and pull up to the bottom
String matching: find a substring in a string
Retirement plan fails, 64 year old programmer starts work again
Preparation for school and professional cognition
Current market situation and development prospect forecast of the global fire boots industry in 2022
Why does I start with =1? How does this code work?
Market status and development prospect prediction of global SoC Test Platform Industry in 2022
1099 build a binary search tree (30 points)
Market status and development prospect prediction of global neutral silicone sealant industry in 2022
Basic use of Metasploit penetration testing framework
Current market situation and development prospect forecast of global UV sensitive resin 3D printer industry in 2022

