0

mp3 在屏幕锁定时暂停..这是我的主要 java 代码...我搜索了一些信息,但没有任何帮助。顺便说一下,单击播放后,然后停止,然后重新播放,应用程序强制崩溃,有时它需要更多的点击,有时更少..有人可以帮我吗..谢谢!

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class Main extends Activity implements OnClickListener {

private ProgressBar playSeekBar;

private Button buttonPlay;

private Button buttonStopPlay;

private MediaPlayer player;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initializeUIElements();

    initializeMediaPlayer();
}
private void initializeUIElements() {

    playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
    playSeekBar.setMax(100);
    playSeekBar.setVisibility(View.INVISIBLE);

    buttonPlay = (Button) findViewById(R.id.buttonPlay);
    buttonPlay.setOnClickListener(this);

    buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
    buttonStopPlay.setEnabled(false);
    buttonStopPlay.setOnClickListener(this);

}
public void onClick(View v) {
    if (v == buttonPlay) {
        startPlaying();
    } else if (v == buttonStopPlay) {
        stopPlaying();
    }
}  
private void startPlaying() {
    buttonStopPlay.setEnabled(true);
    buttonPlay.setEnabled(false);

    playSeekBar.setVisibility(View.VISIBLE);

    player.prepareAsync();

    player.setOnPreparedListener(new OnPreparedListener() {

        public void onPrepared(MediaPlayer mp) {
            player.start();
        }
    });

}

private void stopPlaying() {
    if (player.isPlaying()) {
        player.stop();
        player.release();
        initializeMediaPlayer();
    }

    buttonPlay.setEnabled(true);
    buttonStopPlay.setEnabled(false);
    playSeekBar.setVisibility(View.INVISIBLE);
}

private void initializeMediaPlayer() {
    player = new MediaPlayer();
    try {
        player.setDataSource("http://users1.jabry.com/mine/inna.mp3");
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            playSeekBar.setSecondaryProgress(percent);
            Log.i("Buffering", "" + percent);
        }
    });
}

@Override
protected void onPause() {
    super.onPause();
    if (player.isPlaying()) {
        player.stop();
    }
}
}
4

1 回答 1

1

当屏幕被锁定时,您的 onPause 被调用,并且您明确地在那里停止播放器。

于 2013-02-23T03:45:25.203 回答