2

基本上,在一个简短的解释中,我正在制作一个音板。运行初始活动后,它会将所有声音剪辑添加到声音池。然后我有另外两个活动来组织声音剪辑,我想使用以前加载的声音池,以便在活动之间切换时没有移动加载时间。我对这个 Android 编码相当陌生,所以请用简单的术语来做事情!

编辑:另外,有人知道如何在第二个按钮单击时停止播放吗?不像单击不同的按钮,我理解,但是如果单击相同的按钮,它会停止吗?

我的主要活动:

private SoundManager mSoundManager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);      
    setContentView(R.layout.main);
    mSoundManager = new SoundManager();
    mSoundManager.initSounds(getBaseContext());
    mSoundManager.addSound(0, R.raw.stop_playing);
    mSoundManager.addSound(1, R.raw.sound1);
    mSoundManager.addSound(2, R.raw.sound2);
    mSoundManager.addSound(3, R.raw.sound3);

处理soundpool的东西:

public void initSounds(Context theContext) { mContext = theContext; mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); mSoundPoolMap = new HashMap<Integer, Integer>(); mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}

public void addSound(int Index,int SoundID)
{
    mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));

}

public void pauseSound(){
    mSoundPool.autoPause();
}

public void stopSound(){
    mSoundPool.stop(playingNumber);
}


public int playSound(int index) { 

     int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     int soundId = mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
     mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f); 
     playingNumber = index;
     return playingNumber;
}

}

4

1 回答 1

0

Alwade 创建 Application 类,并在您的应用程序类中创建静态 SoundManager 实例,并在 Initial 活动中将所需的声音添加到 SoundManager。然后您可以在其他活动中使用当前的 Soundmanager。将 SoundManager 类更改为静态类。

例如:

public class MyApplication extends Application {

    public static SoundManager soundManager;

    public static SoundManager getSoundManager() {
        return soundManager;
    }

    public static void setSoundManager(SoundManager soundManagerIns) {
        soundManager = soundManagerIns;
    }

}

并在初始活动中创建实例并将其设置为:

mSoundManager = new SoundManager();
mSoundManager.initSounds(getApplicationContext);
mSoundManager.addSound(0, R.raw.stop_playing);
mSoundManager.addSound(1, R.raw.choo_choo);
mSoundManager.addSound(2, R.raw.all);
mSoundManager.addSound(3, R.raw.hearts);

MyApplication.setSoundManager(mSoundManager);

然后你可以在其他活动中获取这个 SoundManager:

SoundManager sManager = MyApplication.getSoundManager();

这是我的示例项目:SoundPoolExample

于 2013-04-28T05:52:56.740 回答