0

我怎样才能获得完成的重复值mp.setLooping(true)。我可以OnCompletionListener用来获取重复次数,但它会在循环之间产生 1 秒的延迟,这在面向音乐的应用程序中很烦人。OnCompletionListener循环不像mp.setLooping(true).

有什么建议么 ?预先感谢。

循环之间有 1 秒延迟或间隙的代码:

public class MainActivity extends Activity {
MediaPlayer mp1;
Button play;
int maxCount=10,n=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    play = (Button) findViewById(R.id.button1);
    mp = MediaPlayer.create(MainActivity.this, R.raw.soundfile);
    play.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mpplay();
        }
    });

}
private void mpplay() {
    mp1.start();
    mp1.setOnCompletionListener(new OnCompletionListener() {        
        @Override
        public void onCompletion(MediaPlayer mp1) {
            if (n <= maxCount) {
                mp1.start();
                n++;
                if (n >= maxCount) {
                    n = 1;
                    mp1.stop();
                }
            }
        }
    });
}}
4

1 回答 1

3

试试这个:

MediaPlayer mp1;
double play_times = 10;
int sound_length;
Handler handler;
boolean sound_playing = false;
int times_played = 0;

public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.home);
    handler = new Handler();
    mp1 = MediaPlayer.create(this, R.raw.soundfile);
    sound_length = mp1.getDuration();
    mpplay();

}
private void mpplay() {
    times_played = 0;
    mp1.setLooping(true);
    mp1.start();
    sound_playing = true;
    handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));
    handler.postDelayed(counter, sound_length);

}
private Runnable loop_stopper = new Runnable() {
    public void run() {
        sound_playing = false;
        mp1.setLooping(false);
    }
};
private Runnable counter = new Runnable() {
    public void run() {
        if (sound_playing) {
            times_played++;
            handler.postDelayed(counter, sound_length);
        }
    }
};

handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));

此行将在最后一个所需循环的中途停止循环。由于这只是意味着它不会继续循环播放,因此声音文件仍将在最后一次重复时完全播放。

于 2013-05-05T06:06:52.653 回答