用onClick播放两个声音

时间:2013-06-17 16:05:20

标签: android audio media-player

当用户点击按钮

时,我想播放两个不同的声音文件
@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        playSound(this,R.raw.s1);
        playSound(this,R.raw.s2);

    }

    public static void playSound(Context context, int soundID){      
        MediaPlayer mp = MediaPlayer.create(context, soundID); 
        mp.start();
        }

这个代码的问题是s1和s2文件同时播放,我想播放s1然后如果s1 finsh播放s2文件,我该怎么办?

2 个答案:

答案 0 :(得分:0)

试试这个:

int[] sounds = new int[] {R.raw.s1, R.raw.s2};    
int counter = 0;

@Override
public void onClick(View v) {
    playSound(sounds[counter]);
}

public void playSound(Context context, int soundID){      
    MediaPlayer mp = MediaPlayer.create(context, soundID); 
    mp.setOnCompletionListener(this);
    mp.start();
}

@Override
public void onCompletion(MediaPlayer mp) {
    counter++;
    if (counter < sounds.length) {   
        playSound(sounds[counter]);
    }
}

这不是我写过的最优雅的东西,但它应该满足你的要求。

答案 1 :(得分:0)

试试这个:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    MediaPlayer mp = MediaPlayer.create(context,R.raw.s1); 
    mp.start();
    mp.setOnCompletionListener(new OnCompletionListener() 
    {
        public void onCompletion(MediaPlayer mp2){   

            mp2 = MediaPlayer.create(context,R.raw.s2); 
            mp2.start();
        }
    });
}