Android Programming - How to play a SoundPool sound from a broadcastreceiver?
I'm very new to Android development and would like to know how to play a SoundPool sound within a broadcastreceiver?
I read somewhere th开发者_JAVA百科at using SoundPool is the way go play the sound but I don't know how to set it up properly.
I have some sound files such as wave and mp3 files in my Eclipse res\raw folder. I would like to play a file called half.wav
Can you show example code I need to place into my broadcastreceiver?
Here is a first attempt at the code but I do get an error stating that soundID = soundPool.load(this, R.raw.half, 1);
"The Method Load(Context, Int, Int) In The Type SoundPool Is Not Applicable..."
Here is the code for the class:
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();
}
}
}
Thanks in advance.
Truly, Emad
If it is just one sound you want to play I think using the MediaPlayer would be quicker and easier...
This is the code from an app of mine that plays a beep every 30 minutes when this Broadcastreceiver runs
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 {
}
}
}
}
精彩评论