在ListView中选择新歌曲时,MediaPlayer将停止当前歌曲

时间:2018-09-08 14:19:04

标签: java android listview

我正在使用ListView编写音乐播放器应用。当我单击MainActivity上的歌曲时,它会打开nowplaying活动并开始播放一首歌曲,但是如果我返回到ListView并单击新歌曲,则新歌曲在上一首歌曲仍在播放时开始播放,因此两首歌曲同时播放。

我如何做到使当单击新歌曲时,上一首歌曲停止并开始新歌曲?以下是我的MainActivity

代码
public class nowPlaying extends AppCompatActivity implements View.OnClickListener {

Button rewindButton, pauseAndPlayButton, fastForwardButton;
TextView songNameID, artistNameID, details, detailsText;
ImageView musicLogo;
SeekBar seekBar;
public static MediaPlayer mediaPlayer;
public Runnable runnable;
public Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_now_playing);

    TextView nowPlayingID = findViewById(R.id.now_playing_id);
    songNameID = findViewById(R.id.song_name_id);
    artistNameID = findViewById(R.id.artist_name_id);
    rewindButton = findViewById(R.id.rewind_button);
    pauseAndPlayButton = findViewById(R.id.pause_and_play_button);
    fastForwardButton = findViewById(R.id.fast_forward_button);
    detailsText = findViewById(R.id.details_text);
    details = findViewById(R.id.details_id);
    seekBar = findViewById(R.id.seekbar_id);
    musicLogo = findViewById(R.id.music_logo);
    handler = new Handler();

    nowPlayingID.setText(R.string.now_playing);
    rewindButton.setText("<<");
    pauseAndPlayButton.setText(R.string.ii);
    fastForwardButton.setText(">>");
    details.setText(R.string.about_song);

    String nameSong = getIntent().getStringExtra("name");
    String nameArtist = getIntent().getStringExtra("artist");

    if (nameSong.equals("Shape of you") && nameArtist.equals("ed sheeran")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_ed_sheeran);
        musicLogo.setImageResource(R.drawable.shape_of_you);

        mediaPlayer = MediaPlayer.create(this, R.raw.sheeran);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }

    else if (nameSong.equals("Friends") && nameArtist.equals("marshmello & anne-marie")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_marshmello);
        musicLogo.setImageResource(R.drawable.marshmello);

        mediaPlayer = MediaPlayer.create(this, R.raw.marshmello);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }

    else if (nameSong.equals("L'Hiver Indien") && nameArtist.equals("baloji")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_baloji);
        musicLogo.setImageResource(R.drawable.baloji);

        mediaPlayer = MediaPlayer.create(this, R.raw.baloji);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }

    else if (nameSong.equals("Ye") && nameArtist.equals("burna boy")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_burna);
        musicLogo.setImageResource(R.drawable.burna);

        mediaPlayer = MediaPlayer.create(this, R.raw.burna);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }

    else if (nameSong.equals("What lovers do") && nameArtist.equals("maroon 5 ft. sza")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_maroon);
        musicLogo.setImageResource(R.drawable.maroon_five);

        mediaPlayer = MediaPlayer.create(this, R.raw.maroon);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }

    else if (nameSong.equals("Live in the moment") && nameArtist.equals("portugal. the man")) {
        songNameID.setText(nameSong);
        artistNameID.setText(nameArtist);
        detailsText.setText(R.string.details_portugal);
        musicLogo.setImageResource(R.drawable.portugal_man);

        mediaPlayer = MediaPlayer.create(this, R.raw.portugal);

        rewindButton.setOnClickListener(this);
        pauseAndPlayButton.setOnClickListener(this);
        fastForwardButton.setOnClickListener(this);


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                seekBar.setMax(mediaPlayer.getDuration());
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                else {
                    mediaPlayer.start();
                    changeSeekbar();
                }
            }
        });
    }





    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            if (b) {
                mediaPlayer.seekTo(i);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

public void changeSeekbar() {
    seekBar.setProgress(mediaPlayer.getCurrentPosition());
    if (mediaPlayer.isPlaying()) {
        runnable = new Runnable() {
            @Override
            public void run() {
                changeSeekbar();
            }
        };
        handler.postDelayed(runnable, 1000);
    }
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.pause_and_play_button:
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                pauseAndPlayButton.setText(">");
            }
            else {
                mediaPlayer.start();
                pauseAndPlayButton.setText("||");
                changeSeekbar();
            }
            break;

        case R.id.fast_forward_button:
            mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 5000);
            break;

        case R.id.rewind_button:
            mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 5000);
            break;
    }
}
}    

2 个答案:

答案 0 :(得分:0)

切换到新的音频文件时,必须先将mediaPlayer指针/变量标为空,然后再分配新的音频源

    Uri queryUri = MediaStore.Files.getContentUri("external");
    String columnData = MediaStore.Files.FileColumns.DATA;
    String columnSize = MediaStore.Files.FileColumns.SIZE;

    String[] projectionData = {MediaStore.Files.FileColumns.DATA};


    String name = null;
    String size = null;

    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if ((cursor != null)&&(cursor.getCount()>0)) {
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);

        cursor.moveToFirst();

        name = cursor.getString(nameIndex);
        size = cursor.getString(sizeIndex);

        cursor.close();
    }

    if ((name!=null)&&(size!=null)){
        String selectionNS = columnData + " LIKE '%" + name + "' AND " +columnSize + "='" + size +"'";

        Cursor cursorLike = getContentResolver().query(queryUri, projectionData, selectionNS, null, null);

        if ((cursorLike != null)&&(cursorLike.getCount()>0)) {
            cursorLike.moveToFirst();
            int indexData = cursorLike.getColumnIndex(columnData);
            if (cursorLike.getString(indexData) != null) {
                result = cursorLike.getString(indexData);
            }
            cursorLike.close();
        }
    }

    return result;

答案 1 :(得分:0)

对于迟到的答案很抱歉,但您正在寻找的答案非常简单,您需要在 OnClick

中执行时检查适配器类
holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, PlayerActivity.class);
            intent.putExtra("sender", "fromSongList");//ignore this
            intent.putExtra("position", position);
            if (mediaPlayer!=null){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            context.startActivity(intent);
        }
    });