2

我创建了一个歌曲播放器,它具有播放、暂停、下一首等基本功能。当我点击播放按钮时,当前歌曲索引将播放。现在,当歌曲正在播放时,我按下后退按钮使用意图进入我的家庭活动,歌曲仍在播放。但是当我点击播放器按钮进入播放器时,我的播放/暂停按钮的状态是播放,当我点击播放按钮时,我的歌曲索引的默认索引(currentSongIndex(1))会播放,我播放的最后一首歌仍然是玩。因此,有 2 首歌曲同时播放。我该如何解决这个问题?

我想创建一个即使退出应用程序也能在后台运行的音乐播放器。任何帮助将不胜感激。

这是代码。包 com.hirou.player;

public class HirouMusic extends Activity implements OnCompletionListener,
        SeekBar.OnSeekBarChangeListener {

protected static final int RESULT_SPEECH = 1;
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songAlbum;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private Button details;
private ImageView songAlbumArt;
private ProgressDialog details_dialog;
// Media Player
private  MediaPlayer mp;


// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 20000; // 20000 milliseconds
private int seekBackwardTime = 20000; // 20000 milliseconds
public int currentSongIndex = 0; 
public int currentSongIndexResume;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.player);


// All player buttons
    btnPlay = (ImageButton) findViewById(R.id.btnPlay);
    btnForward = (ImageButton) findViewById(R.id.btnForward);
    btnBackward = (ImageButton) findViewById(R.id.btnBackward);
    btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
    btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
    songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) findViewById(R.id.songTitle);
    songAlbum = (TextView) findViewById(R.id.songAlbum);
    songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
    details =(Button) findViewById(R.id.btnDetails);
    songAlbumArt = (ImageView) findViewById(R.id.songAlbumArt);




        mp = new MediaPlayer();

    //Getting songs from SongsManager Class stored in arrayList
        songManager = new SongsManager();

        utils = new Utilities();

        // Listeners
        songProgressBar.setOnSeekBarChangeListener(this); // Important
        mp.setOnCompletionListener(this); // Important

        // Getting all songs list
        songsList = songManager.getPlayList(this);

        // By default play first song
        //playSong(0);




        btnPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // check for already playing
                if(mp.isPlaying()){

                    if(mp!=null){
                        mp.pause();

                        btnPlay.setImageResource(R.drawable.btn_play);
                    }
                }else{
                    // Resume song
                    IS_PLAYING=false;
                    if(mp!=null){
                        mp.start();
                        // Changing button image to pause button
                        btnPlay.setImageResource(R.drawable.btn_pause);
                    }
                }

            }
        });


        btnForward.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // get current song position                
                int currentPosition = mp.getCurrentPosition();
                // check if seekForward time is lesser than song duration
                if(currentPosition + seekForwardTime <= mp.getDuration()){
                    // forward song
                    mp.seekTo(currentPosition + seekForwardTime);
                }else{
                    // forward to end position
                    mp.seekTo(mp.getDuration());
                }
            }
        });


        btnBackward.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // get current song position                
                int currentPosition = mp.getCurrentPosition();
                // check if seekBackward time is greater than 0 sec
                if(currentPosition - seekBackwardTime >= 0){
                    // forward song
                    mp.seekTo(currentPosition - seekBackwardTime);
                }else{
                    // backward to starting position
                    mp.seekTo(0);
                }

            }
        });

        /**
         * Next button click event
         * Plays next song by taking currentSongIndex + 1
         * */
        btnNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if(isShuffle){
                    Random rand = new Random();
                    currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
                    playSong(currentSongIndex);
                }
                else{
                            // check if next song is there or not
                        if(currentSongIndex < (songsList.size() - 1)){
                            playSong(currentSongIndex + 1);
                            currentSongIndex = currentSongIndex + 1;
                        }else{
                            // play first song
                            playSong(0);
                            currentSongIndex = 0;
                            }   
                }

            }
        });

        /**
         * Back button click event
         * Plays previous song by currentSongIndex - 1
         * */
        btnPrevious.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(currentSongIndex > 0){
                    playSong(currentSongIndex - 1);
                    currentSongIndex = currentSongIndex - 1;
                }else{
                    // play last song
                    playSong(songsList.size() - 1);
                    currentSongIndex = songsList.size() - 1;
                }

            }
        });

        /**
         * Button Click event for Repeat button
         * Enables repeat flag to true
         * */
        btnRepeat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(isRepeat){
                    isRepeat = false;
                    Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                    btnRepeat.setImageResource(R.drawable.btn_repeat);
                }else{
                    // make repeat to true
                    isRepeat = true;
                    Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                    // make shuffle to false
                    isShuffle = false;
                    btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                    btnShuffle.setImageResource(R.drawable.btn_shuffle);
                }   
            }
        });

        /**
         * Button Click event for Shuffle button
         * Enables shuffle flag to true
         * */
        btnShuffle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(isShuffle){
                    isShuffle = false;
                    Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                    btnShuffle.setImageResource(R.drawable.btn_shuffle);
                }else{
                    // make repeat to true
                    isShuffle= true;
                    Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                    // make shuffle to false
                    isRepeat = false;
                    btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                    btnRepeat.setImageResource(R.drawable.btn_repeat);
                }   
            }
        });

        /**
         * Button Click event for Play list click event
         * Launches list activity which displays list of songs
         * */
        btnPlaylist.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
                startActivityForResult(i, 100);         
            }
        });

        //---------- Details Button ----------------------------
        details.setOnClickListener(new View.OnClickListener() {

            private ProgressDialog details_dialog;

            @Override
            public void onClick(View arg0) {

                String songTitle = songsList.get(currentSongIndex).get("songTitle");
                String songArtist = songsList.get(currentSongIndex).get("songArtist");
                String songDuration = songsList.get(currentSongIndex).get("songDuration");
                String songPath = songsList.get(currentSongIndex).get("songPath");

                Log.d(getClass().getName(), "Showing Dialog");
                this.details_dialog = ProgressDialog.show(HirouMusic.this, "", "Title : " +songTitle +"\n"
                        + "Artist : " +songArtist+"\n" + "Duration : " + songDuration + "\n" + "Song Path : "
                        + songPath ,true);
                this.details_dialog.setCancelable(true);


            }
        });

    }

/**
 * Receiving song index from playlist view and play the song
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 100) { 
        currentSongIndex = data.getExtras().getInt("songIndex");
        // play selected song
        playSong(currentSongIndex);
    }


} // end

/**
 * Function to play a song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();
        // Displaying Song title
        String songTitle = songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);
        String songAlbum2 = songsList.get(songIndex).get("songArtist");
        songAlbum.setText(songAlbum2);



        // Changing Button Image to pause image
        btnPlay.setImageResource(R.drawable.btn_pause);

        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);

        // Updating progress bar
        updateProgressBar();            
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) { 
        e.printStackTrace();
    }
}

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);        
}   

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 * 
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF
    if(isRepeat){
        // repeat is on play same song again
        playSong(currentSongIndex);
    } else if(isShuffle){
        // shuffle is on - play a random song
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        // no repeat or shuffle ON - play next song
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
        }
    }
}    

@Override
public void onBackPressed() {

// ==== this is where I go to my home activity  

            Intent intent = new Intent(HirouMusic.this, Home.class);
            startActivity(intent);

            super.onBackPressed();

返回; }

}`

4

3 回答 3

0

这样做:

@Override
    protected void onPause() {
        super.onPause();
        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }
于 2013-08-24T08:46:19.770 回答
0
@Override
public void onBackPressed() {

        mp.pause();
        Intent intent = new Intent(HirouMusic.this, Home.class);
        startActivity(intent);

        super.onBackPressed();
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) { 
    mp.start();
  }
} 

理论上,这将保存最后一首歌曲播放的数据并在再次创建活动时播放它,即使它使用暂停。试试看

于 2014-10-28T23:21:57.690 回答
0

您可以简单地使用适用于 android 的Songig MusicPlayer 库。Songig 处理您所有的音乐播放列表,并让您通过许多回调来管理您的列表。您可以将许多 ui 绑定到 songig 以在需要时更改它们。例如,您可以将 2 个搜索栏绑定到 Songig,并且 Songig 将在每次更新中更改它们的进度。

于 2016-02-09T17:15:37.707 回答