当前位置:网站首页>Audio Focus Series: write a demo to understand audio focus and audiomananger
Audio Focus Series: write a demo to understand audio focus and audiomananger
2022-07-03 05:04:00 【zhangjin1120】
Catalog
Let's see the test results first :
- To open the first demo, Click on “start” wait a while ( Local audio loading takes time ), The sound of the car will be played in cycles .
- home Key back to desktop , Find cool dog music APP And open , Play a song , At this time logcat It will print
AUDIOFOCUS_LOSS,Demo App Will pause the play . - Manually pause the cool dog music player (log There will be no change , That is, there is no trigger
AUDIOFOCUS_GAIN). - set alarm , Alarm clock trigger ,log Show
AUDIOFOCUS_LOSS_TRANSIENT - Turn off the alarm clock ,log Show
AUDIOFOCUS_GAIN
![]() ![]() |
Demo Source code
The layout file is just a button , Write your own layout , complete Demo The code is as follows , The notes are very clear , No explanation .
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() {
// initialization AudioManager object
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Application focus
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
AssetFileDescriptor fileDescriptor;
try {
// Get audio files
fileDescriptor = this.getAssets().openFd("11582.mp3");
// Instantiation MediaPlayer object
mMediaPlayer = new MediaPlayer();
// Set the playback stream type
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// Set the playback source , There are multiple parameters to choose , Refer to relevant documents for details , This article aims to introduce audio focus
mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
// Set up looping
mMediaPlayer.setLooping(true);
// Ready to monitor
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// Automatically play after preparation
mMediaPlayer.start();
}
});
// Asynchronous preparation
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();
}
/** * Focus change listener */
private AudioManager.OnAudioFocusChangeListener mAudioFocusChange = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for a long time
Log.d(TAG, "AUDIOFOCUS_LOSS");
stop();
// Release focus
mAudioManager.abandonAudioFocus(mAudioFocusChange);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Temporary loss of focus
stop();
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Temporarily lose focus and reduce sound
Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
case AudioManager.AUDIOFOCUS_GAIN:
// Regain focus
Log.d(TAG, "AUDIOFOCUS_GAIN");
start();
break;
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.release();
mAudioManager.abandonAudioFocus(mAudioFocusChange);
}
}
What are the practical scenarios of audio focus ?
- Turn on cool dog music and play a song , And on again B standing , Play the video , At this time, cool dog will automatically pause , Press the back key to exit the video playback , Cool dog will automatically resume playing music .
How does the official website describe the audio focus ?
边栏推荐
- Market status and development prospect prediction of global SoC Test Platform Industry in 2022
- 1095 cars on campus (30 points)
- Shell script Basics - basic grammar knowledge
- Market status and development prospect prediction of the global fire alarm sensor industry in 2022
- How to connect the network: Chapter 1 CSDN creation punch in
- Market status and development prospect prediction of global colorimetric cup cover industry in 2022
- Prepare for 2022 and welcome the "golden three silver four". The "summary of Android intermediate and advanced interview questions in 2022" is fresh, so that your big factory interview can go smoothly
- 1107 social clusters (30 points)
- Mobile terminal - uniapp development record (public request encapsulation)
- Thesis reading_ Chinese NLP_ ELECTRA
猜你喜欢

5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip

Thesis reading_ Chinese medical model_ eHealth

Promise

Prepare for 2022 and welcome the "golden three silver four". The "summary of Android intermediate and advanced interview questions in 2022" is fresh, so that your big factory interview can go smoothly

Learn to use the idea breakpoint debugging tool

Handler understands the record

移动端——uniapp开发记录(公共请求request封装)

Online VR model display - 3D visual display solution

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

Valentine's day limited withdrawal guide: for one in 200 million of you
随机推荐
Current market situation and development prospect forecast of the global fire boots industry in 2022
Market status and development prospect prediction of global SoC Test Platform Industry in 2022
[luatos sensor] 2 air pressure bmp180
Use posture of sudo right raising vulnerability in actual combat (cve-2021-3156)
1111 online map (30 points)
Do you know UVs in modeling?
1118 birds in forest (25 points)
Force GCC to compile 32-bit programs on 64 bit platform
1087 all roads lead to Rome (30 points)
Self introduction and objectives
Three representations of signed numbers: original code, inverse code and complement code
[luatos sensor] 1 light sensing bh1750
Blog building tool recommendation (text book delivery)
Thesis reading_ Tsinghua Ernie
LVS load balancing cluster of efficient multi-purpose cluster (NAT mode)
Realize file download through the tag of < a > and customize the file name
Source insight garbled code solution
Market status and development prospect prediction of global neutral silicone sealant industry in 2022
Thesis reading_ ICD code_ MSMN
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree

