Android编程 - 如何从广播接收器播放SoundPool声音?

Ema*_*een 3 android broadcastreceiver

我对Android开发很陌生,想知道如何在广播接收器中播放SoundPool声音?

我在某处读到使用SoundPool是播放声音的方式,但我不知道如何正确设置它.

我的Eclipse res\raw文件夹中有一些声音文件,如wave和mp3文件.我想播放一个名为half.wav的文件

你能展示我需要放入我的广播接收器的示例代码吗?

这是对代码的第一次尝试,但我得到一个错误,声明soundID = soundPool.load(this,R.raw.half,1);

"类型SoundPool中的方法加载(Context,Int,Int)不适用......"

这是该类的代码:

package ChimeMe.BigBen;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.os.Bundle;

import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;

public class AlarmReceiver extends BroadcastReceiver {

private SoundPool soundPool;
private int soundID;
boolean loaded = false;

@Override
public void onReceive(Context context, Intent intent) {

    try {

        // Load the sound
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId,
                    int status) {
                loaded = true;
            }
        });

        soundID = soundPool.load(this, R.raw.half, 1);

        Toast.makeText(context, "This is the alarm.", Toast.LENGTH_SHORT)
                .show();

    } catch (Exception e) {
        Toast.makeText(
                context,
                "There was an error somewhere, but we still received an alarm",
                Toast.LENGTH_SHORT).show();
        e.printStackTrace();

    }
}

}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

真的,Emad

Phe*_*105 6

如果它只是你想要播放的一种声音,我认为使用MediaPlayer会更快更容易......

这是来自我的应用程序的代码,当此Broadcastreceiver运行时,每30分钟发出一声哔声

public class Gameloop extends BroadcastReceiver {
    MediaPlayer mp = null;// Here 
    private static final String TAG = "VPET";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Loop running");
        if (Pet.isAlive == true) {

            mp = MediaPlayer.create(context, R.raw.beep);//Onreceive gives you context
            mp.start();// and this to play it

        } else {

        }
    }


}

}
Run Code Online (Sandbox Code Playgroud)