Android play background music android button audio at the same time
16lz
2021-01-23
import android.content.Context;import android.media.AudioManager;import android.media.MediaPlayer;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.support.annotation.RawRes;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Toast;import java.util.HashMap;public class MainActivity extends AppCompatActivity { MediaPlayer mediaPlayer; SoundPool soundPool; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mediaPlayer = playBackgroundMusic(this, R.raw.audio_bg, true); findViewById(R.id.main_play_audio).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { soundPool = playSoundPoolAudio(R.raw.audio_pup_window); } }); } @Override protected void onResume() { super.onResume(); if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } soundPool.autoResume(); } @Override protected void onPause() { super.onPause(); if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } soundPool.autoPause(); } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.release(); } private MediaPlayer playBackgroundMusic(Context context, @RawRes int res, boolean loop) { MediaPlayer mp; mp = MediaPlayer.create(context, res); mp.setLooping(loop); mp.start(); Toast.makeText(context, "Play background music!", Toast.LENGTH_SHORT).show(); return mp; } private SoundPool playSoundPoolAudio(@RawRes int res) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); assert am != null; float currentStreamVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC); float maxStreamVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float setVolume = currentStreamVolume / maxStreamVolume; SoundPool sp; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { sp = new SoundPool.Builder() .setMaxStreams(3) .build(); } else { sp = new SoundPool(3, AudioManager.STREAM_MUSIC, 1); } HashMap hm = new HashMap<>(); hm.put("audio_1", sp.load(this, res, 0)); sp.play(hm.get("audio_1"), setVolume, setVolume, 1, 0, 1.0f); Toast.makeText(MainActivity.this, "Play audio! ", Toast.LENGTH_SHORT).show(); return sp; }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer