Android 如何一步将声音从SoundManager加载到所有活动?
我正在尝试找出如何在应用程序中加载各种声音。我的soundmanager工作顺利,如下所示:Android 如何一步将声音从SoundManager加载到所有活动?,android,audio,android-activity,soundpool,Android,Audio,Android Activity,Soundpool,我正在尝试找出如何在应用程序中加载各种声音。我的soundmanager工作顺利,如下所示: package com.beeseries.contextclues; import java.util.HashMap; import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; public class SoundManager { private S
package com.beeseries.contextclues;
import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
private SoundPool mSoundPool;
private HashMap mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int index, int SoundID)
{
mSoundPoolMap.put(index, mSoundPool.load(mContext, SoundID, 1));
}
public void loadWritingSounds(){
mSoundPoolMap.put(0, mSoundPool.load(mContext, R.raw.writing1, 1));
mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.writing2, 1));
mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.writing3, 1));
mSoundPoolMap.put(3, mSoundPool.load(mContext, R.raw.writing4, 1));
mSoundPoolMap.put(4, mSoundPool.load(mContext, R.raw.writing5, 1));
}
public void playSound(int index)
{
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopedSound(int index)
{
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}
我的应用程序的“打开”活动包含以下使声音正常工作的代码片段:
public SoundManager mSoundManager;
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.loadWritingSounds();
以及以下播放随机声音的代码(该代码确实有效,但仅适用于开场活动):
所以我的困境是,我需要能够一次加载所有活动的WritingSounds,因为现在,如果我尝试在另一个活动上播放声音,除非我添加代码片段使soundmanager工作,否则它将无法工作
我该怎么办 您的soundmanager在哪里?它是一个全局对象/单个对象,还是以某种方式绑定到应用程序中?如果您想跨活动使用它,您需要确保它在应用程序的整个生命周期中都有效。如果您对soundmanager的唯一引用是在初始活动中,那么当您的活动结束时,它将被GC’d。嗯,不完全确定您在问什么,但我可以告诉您,我有一个名为soundmanager.java的类,我在初始活动中的引用是该类。另外,刚才注意到SoundManager.java在我的清单文件中没有被引用,我认为每次都需要引用同一个声音管理器,因为我一直在做mSoundManager=new SoundManager();
int b = randSound1.nextInt((whichSound.length));
mSoundManager.playSound(b);