触摸时播放短音

时间:2017-02-19 10:40:05

标签: android touch

我正试图让我的游戏在按下磁贴时发出短促的声音,Android Studio告诉我SoundPool已被弃用,所以有人可以告诉我应该使用的是什么吗?这就是我的SoundPoolPlayer类的样子,它当前导致我的游戏崩溃:

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import java.util.HashMap;

public class SoundPoolPlayer {
    private SoundPool mShortPlayer = null;
    private HashMap mSounds = new HashMap();

    public SoundPoolPlayer(Context pContext) {

        this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);

        mSounds.put(R.raw.click, this.mShortPlayer.load(pContext, R.raw.click, 1));
    }

    public void playShortResource(int piResource) {
        int iSoundId = (Integer) mSounds.get(piResource);
        this.mShortPlayer.play(iSoundId, 0.99f, 0.99f, 0, 0, 1);
    }

    // Cleanup
    public void release() {
        // Cleanup
        this.mShortPlayer.release();
        this.mShortPlayer = null;
    }

}

然后我在游戏活动中使用以下代码播放声音:

SoundPoolPlayer sound = new SoundPoolPlayer(getContext());
sound.playShortResource(R.raw.click);
sound.release();

2 个答案:

答案 0 :(得分:0)

你应该在onTouchListener中使用MediaPlayer,如下所示:

  mPlayer = new MediaPlayer();
            mPlayer.setAudioStreamType(AudioManager.STREAM_RING);

            try {
                mPlayer.setDataSource(mContext,
                        Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.YOUR_FILE_NAME));
                mPlayer.prepare();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Could not setup media player for ringtone");
                mPlayer = null;
                return;
            }
            mPlayer.setLooping(false);
            mPlayer.start();

答案 1 :(得分:0)

为了播放声音,您可以使用Android MediaPlayer。

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.click);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });