简体   繁体   English

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

[英]How to Play sound when button is clicked in Android?

I'm trying to play a sound file when a button is clicked but keeps getting an error. 我正在尝试在单击按钮时播放声音文件,但不断出现错误。

The error is: 错误是:

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

Here's 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 tips would be appreciated. 任何帮助或提示将不胜感激。 Thnx! 日Thnx!

There are a few things going on here (disclaimer, this is just how I'm used to using it, there may be a better way): 这里有一些事情(免责声明,这就是我习惯使用它的方式,可能有更好的方法):

  • You seem to be doing a lot more work per click than you need to. 您似乎每次点击的工作量超出了您的需求。 You're creating and adding a new onClickListener for every click in the Activity's View, not the Button . 您正在为Activity的视图中的每次单击创建并添加新的onClickListener ,而不是Button You only need to set the listener once, and for the Button rather than the overarching View; 您只需要设置一次侦听器,而不是设置Button而不是整体视图; I tend to do that in the constructor of the Activity. 我倾向于在Activity的构造函数中这样做。

  • Regarding your error, MediaPlayer works fine for me when the Context I pass it is the overriding Activity. 关于你的错误,当我传递的Context是覆盖的Activity时,MediaPlayer对我来说很好。 When you pass this , it's passing the onClickListener you are creating, throwing off the MediaPlayer. 当你传递this ,它传递你正在创建的onClickListener ,抛弃MediaPlayer。

  • Finally, to actually play the sound, you have to call start() . 最后,要实际播放声音,您必须调用start()

So for the constructor in the Activity, you can create the MediaPlayer once, find the Button, and attach an onClickListener that will play the sound from the MediaPlayer you've just created. 因此,对于Activity中的构造函数,您可以创建一次MediaPlayer ,找到Button,并附加一个onClickListener ,它将播放您刚刚创建的MediaPlayer的声音。 It would look something like: 它看起来像:

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();
            }
        });
    }
}

Hope that helps! 希望有所帮助!

I have played around with media-player, and it is easy to get in trouble. 我玩过媒体播放器,很容易遇到麻烦。 I followed the advice of Volodymyr, and SoundPool is much easier to manage. 我遵循Volodymyr的建议,SoundPool更容易管理。

MediaPlayer does not like to play more than one sound at the time, like for instance when you have lots of quick tabs on your buttons. MediaPlayer当时不喜欢播放多个声音,例如当你的按钮上有很多快速标签时。 I managed with the following method: 我用以下方法管理:

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

} }

In the constructor I did: 在构造函数中我做了:

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

On click I would then call playSound(mSoundLess): 点击后我会调用playSound(mSoundLess):

Instead I have created a SoundPool helper: 相反,我创建了一个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);
        }
    }
}

Now I init like this: 现在我这样做:

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

and play a sound like this: 并发出这样的声音:

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

Don't forget to call mSoundPoolHelper.release(); 别忘了打电话给mSoundPoolHelper.release(); , for instance in your onDestroy() . ,例如在你的onDestroy() Something similar is needed if you use MediaPlayer. 如果您使用MediaPlayer,则需要类似的东西。

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

the file yoursoundfile must to be in the res/raw folder yoursoundfile文件必须位于res / raw文件夹中

If you really have to invoke the click programmatically because the view has no own sound, i would solve it like that, its the simplest solution and a oneliner 如果你真的必须以编程方式调用点击,因为视图没有自己的声音,我会像那样解决它,它是最简单的解决方案和oneliner

view.playSoundEffect(SoundEffectConstants.CLICK);

very simple and works, if you want to make a layout play a sound you need to put 非常简单和有效,如果你想让布局播放你需要放的声音

android:soundEffectsEnabled="true"

in your xml. 在你的xml中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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