我对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();
}
}
}
提前致谢。
诚然, Emad
答案 0 :(得分: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 {
}
}
}
}