我正在制作一个包含3个活动的Guitar应用,每个活动都包括一个音频功能,使用SoundPool的原因,并且我有66个样本。 我的问题是我必须在每个活动中加载它们,所以我的问题是,有什么方法可以在我的应用启动后立即上传这66个样本,并保持它们在每个活动中加载?
答案 0 :(得分:0)
您可以为SoundPool
使用一个简单的实用程序类。您可以使用公共静态方法,以便可以实例化一次并从任何活动中对其进行访问。这里是一个可以用于您的案例的类:
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.util.Log;
public class SoundPoolManager {
private static final String TAG = SoundPoolManager.class.getSimpleName();
private static SoundPool soundPool;
private static int[] sm;
private Context context;
private static float mVolume;
private static SoundPoolManager instance;
private static final int SOUND_TOTAL = 1;
private SoundPoolManager(Context context) {
this.context = context;
initSound();
// add sound here
// here the sample audio file which can be use with your audio file
int soundRawId = R.raw.watch_tick;
//you need to change SOUND_TOTAL for the size of the audio samples.
sm[sm.length - 1] = soundPool.load(context, soundRawId, 1);
}
public static void instantiate(Context context) {
if(instance == null) instance = new SoundPoolManager(context);
}
private void initSound() {
sm = new int[SOUND_TOTAL];
int maxStreams = 1;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
soundPool = new SoundPool.Builder()
.setMaxStreams(maxStreams)
.build();
} else {
soundPool = new SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0);
}
mVolume = setupVolume(context);
}
private float setupVolume(Context context) {
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if(am == null) {
Log.e(TAG, "Can't access AudioManager!");
return 0;
}
float actualVolume = (float) am.getStreamVolume(AudioManager.STREAM_ALARM);
float maxVolume = (float) am.getStreamMaxVolume(AudioManager.STREAM_ALARM);
return actualVolume / maxVolume;
}
public static void playSound(int index) {
if(sm == null) {
Log.e(TAG, "sm is null, this should not happened!");
return;
}
if(soundPool == null) {
Log.e(TAG, "SoundPool is null, this should not happened!");
return;
}
if(sm.length <= index) {
Log.e(TAG, "No sound with index = " + index);
return;
}
if(mVolume > 0) {
soundPool.play(sm[index], mVolume, mVolume, 1, 0, 1f);
}
}
public static void cleanUp() {
sm = null;
if(soundPool != null) {
soundPool.release();
soundPool = null;
}
}
}
然后您可以在以下类别中使用该类:
// need to call this for the first time
SoundPoolManager.instantiate(context);
// play the sound based on the index
SoundPoolManager.playSound(index);
// clear up the SoundPool when you don't need it anymore.
SoundPoolManager.cleanUp();