如何在Android中单击按钮时播放声音?

Gre*_*zer 5 android

我正在尝试在单击按钮时播放声音文件,但不断出现错误.

错误是:

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

这是我的代码:

@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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

任何帮助或提示将不胜感激.日Thnx!

pab*_*ier 24

这里有一些事情(免责声明,这就是我习惯使用它的方式,可能有更好的方法):

  • 你似乎每次点击的工作量比你需要的多得多.您正在onClickListener活动视图中的每次点击创建并添加新内容,而不是按钮.您只需要设置一次侦听器,而不是设置Button而不是整体视图; 我倾向于在Activity的构造函数中这样做.

  • 关于你的错误,当我传递的Context是覆盖的Activity时,MediaPlayer对我来说很好.当你通过时this,它正在通过onClickListener你正在创建,抛弃MediaPlayer.

  • 最后,要实际播放声音,你必须打电话start().

因此,对于Activity中的构造函数,您可以创建MediaPlayer一次,找到Button,并附加一个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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!


Jan*_*erg 13

我玩过媒体播放器,很容易遇到麻烦.我遵循Volodymyr的建议,SoundPool更容易管理.

MediaPlayer当时不喜欢播放多个声音,例如当你的按钮上有很多快速标签时.我用以下方法管理:

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

}

在构造函数中我做了:

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

点击后我会打电话 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我这样做:

mSoundPoolHelper = new SoundPoolHelper(1, this);
mSoundLessId = mSoundPoolHelper.load(this, R.raw.less, 1);
mSoundMoreId = mSoundPoolHelper.load(this, R.raw.more, 1);
Run Code Online (Sandbox Code Playgroud)

并发出这样的声音:

private void playSound(int soundId) {
    mSoundPoolHelper.play(soundId);
}
Run Code Online (Sandbox Code Playgroud)

别忘了打电话mSoundPoolHelper.release();,比如在你的电话里onDestroy().如果您使用MediaPlayer,则需要类似的东西.