简体   繁体   中英

How to stop a media player before playing a new song?

I'm working on an app that consist in two activity one that is the media player and the other one that is the list of song to play, the mp3 player is working fine, from the activity with the list i'm passing the name of the song and player works fine. I have two problems, if the user plays a song and leaves the app(the song keeps playing in the background, which is how is suppose to work) then the user return to the app, the seekbar bar is set to 0 and the timer to 0, is there a way to "save" the activity"...also is if one song is playing and the user tries to play another song, the song play on top of the previous song, I try to fix this by adding into my intent a "key" to identifies if is is a new audio and then do something like this: but is not working.

if (playerL != null) {

            if (mediaPlayer.isPlaying()) {
               mediaPlayer.stop;
            }
        }

public class AudioPlayer extends Activity {  

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

        // Header
        Bundle extra = getIntent().getExtras();
        if (extra != null) {
            Intent intent = getIntent();
            id_d    = intent.getStringExtra("Id");
            heading = intent.getStringExtra("Heading"); 
            fileN   = intent.getStringExtra("fileName");
            audioN  = intent.getStringExtra("audioName");
            playerL = intent.getStringExtra("newAudio");

            meet_instructor_round_image = findViewById(R.id.audio_player_img);
            playerHeading = findViewById(R.id.audio_player_heading);
            playerHeading.setText(heading);
            Picasso.with(this).load(imgUrl).transform(new CropCircleTransformation()).into(round_image);
            createNotificationChannel();
            activateNotification(id_d, heading, imgUrl, bio);
        } else {
            Intent intent = new Intent(getApplicationContext(), com.starvizn.newstarvizn.COMMON.Activities.MainActivity.class);
            startActivity(intent);
        }

        pause = findViewById(R.id.btnAudioSubpause);
        play  = findViewById(R.id.btnAudioSubPlay);  

        songName = findViewById(R.id.workoutName);
        initialTime = findViewById(R.id.initialTime); 

        songName.setText(audioN);

        Uri uri = Uri.parse(getApplicationContext().getFilesDir()+"/Downloads/"+fileN+".mp3"); 

        mediaPlayer = MediaPlayer.create(this, uri);
        seekBar = findViewById(R.id.seekBar);
        seekBar.setClickable(false);
        pause.setVisibility(View.INVISIBLE);

        // Open lesson view
        lessons_layout = findViewById(R.id.player_lessons);
        lessons_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "Aqui");
                Intent intent = new Intent(getApplicationContext(), com.myApp.MainActivity.class); 
                intent.putExtra("Id", id_d); 
                startActivity(intent);
            }
        });

        if (playerL != null) {

            if (mediaPlayer.isPlaying()) {

            }
        }
    }

    public void player_play(View view) {
        play.setVisibility(View.INVISIBLE);
        pause.setVisibility(View.VISIBLE);
        mediaPlayer.start();
        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();

        if (oneTimeOnly == 0) {
            seekBar.setMax((int) finalTime);
            oneTimeOnly = 1;
        } 

        initialTime.setText(String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
        );

        seekBar.setProgress((int) startTime);
        myHandler.postDelayed(UpdateSongTime, 100);
        seekBar.setClickable(false);
        pause.setVisibility(View.VISIBLE);
    }

    public void player_pause(View view) {
        pause.setVisibility(View.INVISIBLE);
        play.setVisibility(View.VISIBLE);
        int temp = (int) startTime;

        mediaPlayer.pause();
    }

    public void player_fwd(View view) {
        int temp = (int) startTime;

        if ((temp + fwdTime) <= finalTime) {
            startTime = startTime + fwdTime;
            mediaPlayer.seekTo((int) startTime);
        } else {
            Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds!", Toast.LENGTH_LONG).show();
        }
    }

    public void player_back(View view) {
        int temp = (int) startTime;

        if ((temp - backTime) > 0) {
            startTime = startTime - backTime;
            mediaPlayer.seekTo((int) startTime);
        } else {
            Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_LONG).show();
        }
    }

    private Runnable UpdateSongTime = new Runnable() {
        public void run() {
            startTime = mediaPlayer.getCurrentPosition();
            initialTime.setText(String.format("%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                    TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                    toMinutes((long) startTime)))
            );
            seekBar.setProgress((int) startTime);
            myHandler.postDelayed(this, 100);
        }
    };

    @Override
    public void onBackPressed() {

        builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle("End Player").setMessage("Exit").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
                NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
                notificationManager.cancelAll();
                Intent intent = new Intent(getApplicationContext(), com.myapp.MainActivity.class); 
                intent.putExtra("Id", id_d); 
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    } 


}

So I guess you just need to add the logic which suppose to handle that process. As documentation says you have two methods getCurrentPosition() and seekTo(long, int) So I think you suppose to save current position for example in prefs and resume with help of seekTo method with that data which you saved before. So with help of that you could manage states

When I was working on player app I used ExoPlayer it is more flexible and easier to use. You can try the link below https://codelabs.developers.google.com/codelabs/exoplayer-intro/#0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM