How to play sound when a button is pressed on Android?

I try to play a sound file when a button is pressed, but it continues to receive an error.

Error:

 "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)"

Here is my code:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Button zero = (Button)this.findViewById(R.id.btnZero);
    zero.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(this, R.raw.mamacita_zero);
        }
    });
}

Any help or advice would be appreciated. Thnx!

+5
source share
5 answers

There are several things here (disclaimer, this is how I got used to using it, there may be a better way):

  • It seems you are doing a lot more work per click than you need. You create and add a new one onClickListenerfor each click in the activity view, not in the Button. You only need to set the listener once for the button, and not for a comprehensive view; I usually do this in the Activity constructor.

  • , MediaPlayer , Context pass it . this, onClickListener, MediaPlayer.

  • , , start().

, Activity MediaPlayer , onClickListener, MediaPlayer. :

public class MyActivity extends Activity {

    public MyActivity(Bundle onSavedStateInstance) {
        // eliding some bookkeepping

        MediaPlayer mp = MediaPlayer.create(this, R.raw.mamacita_zero);

        Button zero = (Button)this.findViewById(R.id.btnZero);
        zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

, !

+23

-, . , SoundPool .

MediaPlayer , , . :

private void playSound(Uri uri) {
    try {
        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(this, uri);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    } catch (Exception e) {
        // don't care
    }

}

:

mMediaPlayer = new MediaPlayer();
mSoundLess = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.less);
mSoundMore = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.more);

playSound(mSoundLess):

SoundPool:

package com.mycompany.myapp.util;

import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundPoolHelper extends SoundPool {
    private Set<Integer> mLoaded;
    private Context mContext;

    public SoundPoolHelper(int maxStreams, Context context) {
        this(maxStreams, AudioManager.STREAM_MUSIC, 0, context);
    }

    public SoundPoolHelper(int maxStreams, int streamType, int srcQuality, Context context) {
        super(maxStreams, streamType, srcQuality);
        mContext = context;
        mLoaded = new HashSet<Integer>();
        setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                mLoaded.add(sampleId);
            }
        });
    }

    public void play(int soundID) {
        AudioManager audioManager = (AudioManager) mContext.getSystemService( Context.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 (mLoaded.contains(soundID)) {
            play(soundID, volume, volume, 1, 0, 1f);
        }
    }
}

:

mSoundPoolHelper = new SoundPoolHelper(1, this);
mSoundLessId = mSoundPoolHelper.load(this, R.raw.less, 1);
mSoundMoreId = mSoundPoolHelper.load(this, R.raw.more, 1);

:

private void playSound(int soundId) {
    mSoundPoolHelper.play(soundId);
}

mSoundPoolHelper.release();, , onDestroy(). - , MediaPlayer.

+13
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.yoursoundfile);
mp.start();

yoursoundfile should be in the res / raw folder

+3
source

If you really need to cause a click programmatically because the view does not have its own sound, I would solve it like this, its the simplest solution and oneliner

view.playSoundEffect(SoundEffectConstants.CLICK);

very simple and works, if you want the layout to reproduce sound, you need to put

android:soundEffectsEnabled="true"

in your xml.

0
source

All Articles