当新歌与Service一起播放时如何停止旧歌

时间:2018-05-08 08:40:41

标签: java android android-mediaplayer

我正在尝试创建一个音乐应用。我正在使用此代码在另一首歌曲播放时停止播放该歌曲,但此代码不起作用。两首歌一起播放我想逐个播放,或者如果任何其他歌曲点击停止上一首歌并播放该歌曲。任何人都可以帮助我。

MainActivity:

private void clickSong() {
        mListBaiHat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {    
                String local = mPath.get(i);
                mserviceMusic.setLocalSongRunging(i);   

                try {
                    mserviceMusic.setLocalSong(local);
                    mClickStart.setBackgroundResource(R.drawable.ic_media_pause_light);    

                } catch (IOException e) {
                    e.printStackTrace();
                }    

                mHinhAlbum.setImageResource(arrayList.get(i).getHinhAlbum());
                mCLickTenBaiHat.setText(arrayList.get(i).getTenBaiHat());
                mCLickCasy.setText(arrayList.get(i).getTheloai());    

                    MediaMetadataRetriever retriever = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
                    retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(mPath.get(i));

                    String tenAlbum = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                    String ten = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);

                    mCLickTenBaiHat.setText(ten);
                    mCLickCasy.setText(tenAlbum);

                }

                bundle = new Bundle();
                bundle.putInt("vitri", i);
                bundle.putStringArrayList("tenbai", mPath);


            }
        });
    }

服务:

public void setLocalSongRunging(int vitri){
    mLocaltionSong = vitri;
}

public void setLocalSong(String localsong) throws IOException {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(localsong);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();            
        mediaPlayer.release();
        mediaPlayer=null;

    }else {
        mediaPlayer.prepare();
        mediaPlayer.start();
    }

}

1 个答案:

答案 0 :(得分:0)

您每次都在创建一个新的MediaPlayer。所以你的代码停止和发布不会起作用(因为正在使用不同的媒体播放器实例)在setLocalSong(String localsong)中改变你的代码。

   public void setLocalSong(String localsong) throws IOException {
    if(mediaPlayer != null){
        mediaPlayer.stop();            
        mediaPlayer.release();
        mediaPlayer=null;
    }
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(localsong);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.prepare();
    mediaPlayer.start();

}