我已经实现了soundpool在app启动时播放短音,但由于一些奇怪的原因,它在我打开我的应用程序后停止播放声音,如第24或第25次。与mediaplayer相同的结果。但是当它在第25次发布后停止并且我从我最近的应用程序清除它,它再次开始工作,所以我决定从最近的应用程序列表中排除我的应用程序,但仍然是同样的问题。任何线索?
public class MainActivity extends Activity {
Handler mHandler; // global instance
Runnable your_runnable; // global instance
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//Keep screen Always ON
//final MediaPlayer mp1 = MediaPlayer.create(getBaseContext(), R.raw.a); // -<play mp3
//mp1.start();
mHandler = new Handler();
//your_runnable = new Runnable() {
//@Override
//public void run() {
//Intent startActivity = new Intent(MainActivity.this,
// Activity_2.class); // -<start this activity after 3sec
// startActivity(startActivity);
//overridePendingTransition(R.anim.fadeout, R.anim.fix);//play animation
// finish();
//}
//};
mHandler.postDelayed(your_runnable, 3000L);//3sec timer
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.a, 1);
}
public void onWindowFocusChanged(boolean paramBoolean){//OnCreate Alternate
if (paramBoolean){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
//if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}}
//}
,500);} // 5 minutes delay before execute run()
}
//public void back(View view) {
//mHandler.removeCallbacks(your_runnable);//finishes timer activity before launching new activity
//Intent intent = new Intent(this, Mod_1_1AtoZ.class);
//startActivity(intent);
//overridePendingTransition(R.anim.slide_left_to_right_1,
// R.anim.slide_left_to_right_2);
//finish();
//}
//@Override
//public void onBackPressed() {
// TODO Auto-generated method stub
//}
}
答案 0 :(得分:1)
只需在onLoadComplete
中播放声音播放代码即可。
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
代码将在SoundPool
完成加载声音时执行,因此您不需要实施任何自定义延迟。