Воспроизведение нескольких звуков одновременно в Android - PullRequest
3 голосов
/ 13 апреля 2010

Я не могу использовать следующее для кодирования для одновременного воспроизведения нескольких звуков / звуковых сигналов. По моему onclicklistener я добавил:

public void onClick(View v) { 
     mSoundManager.playSound(1); 
     mSoundManager.playSound(2); 
} 

Но при этом воспроизводится только один звук, звук с индексом 1, за которым следует звук с индексом 2.

Как я могу воспроизводить как минимум 2 звука одновременно, используя этот код, когда есть событие onClick ()?

public class SoundManager {

private  SoundPool mSoundPool; 
private  HashMap<Integer, Integer> mSoundPoolMap; 
private  AudioManager  mAudioManager;
private  Context mContext;


public SoundManager()
{

}

public void initSounds(Context theContext) { 
     mContext = theContext;
     mSoundPool = new SoundPool(4, 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(1, mSoundPool.load(mContext, SoundID, 1));
}

public void playSound(int index) { 

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

public void playLoopedSound(int index) { 

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

}

1 Ответ

6 голосов
/ 05 сентября 2013

Наличие следующего класса для воспроизведения звука с использованием звукового пула:

public class SoundManager {

    public static int SOUNDPOOLSND_MENU_BTN         = 0;
    public static int SOUNDPOOLSND_WIN              = 1;
    public static int SOUNDPOOLSND_LOOSE            = 2;
    public static int SOUNDPOOLSND_DRAW             = 3;
    public static int SOUNDPOOLSND_TICK1            = 4;
    public static int SOUNDPOOLSND_TICK2            = 5;
    public static int SOUNDPOOLSND_OUT_OF_TIME      = 6;
    public static int SOUNDPOOLSND_HISCORE          = 7;
    public static int SOUNDPOOLSND_CORRECT_LETTER   = 8;

    public static boolean isSoundTurnedOff;

    private static SoundManager mSoundManager;

    private SoundPool mSoundPool; 
    private SparseArray <Integer> mSoundPoolMap; 
    private AudioManager  mAudioManager;

    public static final int maxSounds = 4;

    public static SoundManager getInstance(Context context)
    {
        if (mSoundManager == null){
            mSoundManager = new SoundManager(context);
        }

        return mSoundManager;
   }

    public SoundManager(Context mContext)
    {
        mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
        mSoundPool = new SoundPool(maxSounds, AudioManager.STREAM_MUSIC, 0);

//        mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
//            public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
//               loaded = true;
//            }
//        });

        mSoundPoolMap = new SparseArray<Integer>(); 
        mSoundPoolMap.put(SOUNDPOOLSND_MENU_BTN, mSoundPool.load(mContext, R.raw.menubutton, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_WIN, mSoundPool.load(mContext, R.raw.win, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_LOOSE, mSoundPool.load(mContext, R.raw.lose, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_TICK1, mSoundPool.load(mContext, R.raw.tick_0, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_TICK2, mSoundPool.load(mContext, R.raw.tick_1, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_OUT_OF_TIME, mSoundPool.load(mContext, R.raw.out_of_time, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_HISCORE, mSoundPool.load(mContext, R.raw.personal_highscore, 1));
        mSoundPoolMap.put(SOUNDPOOLSND_CORRECT_LETTER, mSoundPool.load(mContext, R.raw.correct_letter, 1));

        // testing simultaneous playing
        int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
        mSoundPool.play(mSoundPoolMap.get(0), streamVolume, streamVolume, 1, 20, 1f); 
        mSoundPool.play(mSoundPoolMap.get(1), streamVolume, streamVolume, 1, 2, 1f);
        mSoundPool.play(mSoundPoolMap.get(2), streamVolume, streamVolume, 1, 0, 1f);


    } 

    public void playSound(int index) { 
        if (isSoundTurnedOff)
            return;

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

    public static void clear()
    {
        if (mSoundManager != null){
            mSoundManager.mSoundPool = null; 
            mSoundManager.mAudioManager = null;
            mSoundManager.mSoundPoolMap = null;
        }
        mSoundManager = null;
    }
}

он воспроизводит одновременно 3 звука, упомянутых ниже комментария "тестирование одновременного воспроизведения". Кажется, вам нужно реализовать комментарий в моем слушателе кода (OnLoadCompleteListener). Может случиться, что система просто не загружает звуки, а вы начинаете ее воспроизводить. Если вы не хотите реализовывать вышеупомянутого слушателя, попробуйте подождать некоторое время после начала воспроизведения звуков и через некоторое время начните воспроизводить звуки.

...