问题描述
- 在activity开始时播放声音
-
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = findViewById(R.id.textView1); view.setOnTouchListener(this); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); 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.dog_bark, 1); } ; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { 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; if (loaded) { soundPool.play(soundID, volume, volume, 1, 0, 1f); } } return false;
}
}代码实现的是在点击事件后声音才会播放。我想要在activity开始后自动播放。然后在播放一遍后,再次点击事件时再播放,谢谢
时间: 2024-10-29 20:37:22