1

嘿伙计们,我在 Android 中使用 MediaPlayer 类时遇到了一个问题

在您建议 SoundPool 之前,我需要在声音片段播放完毕时触发 OnCompletion 事件,否则我会使用它。

所以问题是,当同时激活 3 个或更多剪辑时,我只能获得最后 2 个事件的 OnCompletion,而不是所有事件,任何人都知道这个问题的解决方案或知道它为什么会发生?

// When the user clicks on the Chicken Image, this Function is called
public void onChickenClicked(View view)
{
//  ToastMsg( "You Clicked the Chicken", Toast.LENGTH_SHORT );
    // Then play the sound,
    mMediaPlayer[CHICKEN] = MediaPlayer.create(MainActivity.this, R.raw.chicken_sound );
    // Start playing the sound
    mMediaPlayer[CHICKEN].start();
    // This is to catch when the sound clip has ended, this will be 
    //     used to stop the animation for the chicken
    mMediaPlayer[CHICKEN].setOnCompletionListener( new OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            System.err.println("Chicken On Complete");
            // Stop the animation of the Chicken here
            mAnimation.cancel();
            mAnimation.reset();
            // Then switch the image back to the original Chicken pic
            ImageView imgView = (ImageView) findViewById(R.id.imageViewofChicken);
            imgView.setImageResource(R.drawable.chicken);
            mMediaPlayer[CHICKEN].reset();
        }} );

    // Finds the ImageView, replaces the base img with the alternate img, and plays the sound
    animatePicture( R.id.imageViewofChicken, R.drawable.chicken_tongue);
}   




public void onCowClicked(View view)
{
//  ToastMsg( "You Clicked the Cow", Toast.LENGTH_SHORT );
    // Then play the sound, 
    mMediaPlayer[COW] = MediaPlayer.create(MainActivity.this, R.raw.cow_sound );
    // Start playing the sound
    mMediaPlayer[COW].start();
    // This is to catch when the sound clip has ended, this will be 
    //     used to stop the animation for the chicken
    mMediaPlayer[COW].setOnCompletionListener( new OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            System.err.println("Cow On Complete");
            // Stop the animation of the Chicken here
            mAnimation.cancel();
            mAnimation.reset();
            // Then switch the image back to the original Chicken pic
            ImageView imgView = (ImageView) findViewById(R.id.imageViewofCow);
            imgView.setImageResource(R.drawable.cow);
            mMediaPlayer[COW].reset();
        }} );
    // Finds the ImageView, replaces the base img with the alternate img, and plays the sound
    animatePicture( R.id.imageViewofCow, R.drawable.cow_tongue);
}

//there are more but you get it idea here.

有人对我如何让所有 OnCompleteListeners 触发有任何想法吗?

4

1 回答 1

0

所以我想通了,我只是将MediaPlayer替换为SoundPool,然后使用

private final ScheduledExecutorService mScheduler = Executors.newScheduledThreadPool(MAX_ANIMALS);

处理声音剪辑何时完成,基于我在stackoverflow上看到的一个函数,使用MediaPlayer加载声音,然后以毫秒为单位获取持续时间,并将其用作调度程序的延迟(mScheduler[x])。

这是一个黑客,但它完成了。

于 2014-09-22T23:35:57.037 回答