开发者

How can I get a sound file to play on each click of a button in Android?

I'd like to play a sound as I tap a button like hitting a drum, to have the sound playback as quick as I'm hitting the button. Right now I have to wait for the sound to finish before it will play again. Here's how I've got the sound set up.

MediaPlayer snareMP;

@Override
protected v开发者_JAVA技巧oid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.playdrums);

final MediaPlayer snareMP = MediaPlayer.create(this, R.raw.snare);

ImageView snareDrum = (ImageView) findViewById(R.id.snare);

snareDrum.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            snareMP.reset();
            snareMP.prepare();
            snareMP.start();
        }
    });

Any help is greatly appreciated.

Thanks!


Try this:

public void onClick(View v) {
    if (snareMP.isPlaying()){
        snareMP.stop();
        snareMP.reset();
    }
    snareMP.prepare();
    snareMP.start();
}


I'm going to share a code that I've written a while back which I think does the exact same thing you're looking for; I hope it helps and I'd appreciate some rep points if it does :)

Here it is:

import com.myProject.R;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class Camera extends Activity {

    private MediaPlayer snapMP;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.camera);

        Button snap = (Button)findViewById(R.id.snapButton);
        snap.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                freeSnapMP();
                snapMP = MediaPlayer.create(Camera.this, R.raw.camera_snap2);
                snapMP.start();
            }
        });
    }


    protected void onDestroy() {
        super.onDestroy();
        freeSnapMP();
    }

    private void freeSnapMP(){
        if (snapMP != null){ snapMP.stop(); snapMP.release(); snapMP = null; }
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜