简体   繁体   中英

delay issue when replaying a wav sound in onClick

I have a wav sound that plays when button is pressed and when i attempt to play this again while the sound is still playing there is a short delay and does not start properly as intended! i am trying to have the sound play clean and fast on every press at anytime, here is my java code thank you

 public class MainActivity extends AppCompatActivity { private MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mp = new MediaPlayer(); final ImageView bellImage = (ImageView) findViewById(R.id.bellImage); bellImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loopMP(); mp = MediaPlayer.create(getApplicationContext(), R.raw.ding2); mp.start(); } }); } public void playMusic() { if (mp != null) { mp.start(); } } @Override protected void onDestroy() { if (mp != null && mp.isPlaying()) { mp.stop(); mp.release(); mp = null; } super.onDestroy(); } private void loopMP(){ if (mp != null){ mp.stop(); mp.release(); mp = null; } } } 

Instead of release() and create() the mediaplayer object every time user clicks the button, try to create() only once. Then inside of onClick(), try seekTo(0) to rewind from the beginning of the media file, then call start() to play again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM