gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:38 27 4
gpt4 key购买 nike

我是 Android 开发的新手,想知道如何在广播接收器中播放 SoundPool 声音?

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

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

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

这是对代码的第一次尝试,但我确实收到一条错误消息,指出 soundID = soundPool.load(this, R.raw.half, 1);

“类型 SoundPool 中的方法 Load(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();

}
}

}

提前致谢。

真的,艾玛德

最佳答案

如果您只想播放一种声音,我认为使用 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 {

}
}


}

}

关于Android 编程 - 如何从广播接收器播放 SoundPool 声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7164760/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com