current position:Home>Comprehensive application cases of Android mediaplayer and seekbar

Comprehensive application cases of Android mediaplayer and seekbar

2022-01-26 23:35:04 € € - flying - ~ £

  The code is as follows :

package com.example.musicplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Switch;
import com.example.musicplayer.databinding.ActivityMain2Binding;

public class MainActivity2 extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    private ActivityMain2Binding binding;
    private MediaPlayer mediaPlayer;

    private boolean ok;// Switch of asynchronous thread 

    private int max,progress,index;
    private int[] musics={R.raw.music1,R.raw.music2,R.raw.music3};// Music List 

    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
    }

    private void initView(){
        binding.pause.setOnClickListener(this);
        binding.play.setOnClickListener(this);
        binding.stop.setOnClickListener(this);
        binding.prev.setOnClickListener(this);
        binding.next.setOnClickListener(this);
        musicPlayer();
        handler=new Handler(Looper.getMainLooper()){
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case 100:
                        binding.seekBar2.setProgress(msg.arg1);
                        binding.numberText.setText(timeParse(msg.arg1)+"/"+timeParse(max));
                        break;
                }
            }
        };
        binding.seekBar2.setOnSeekBarChangeListener(this);
        binding.timeText.setText(" The first "+(index+1)+" The first ");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pause:
                if(mediaPlayer!=null && mediaPlayer.isPlaying()){
                    ok=false;
                    mediaPlayer.pause();
                }
                break;
            case R.id.play:
                if(mediaPlayer==null){
                    initPlayer();
                }
                mediaPlayer.start();
//                mediaPlayer.setLooping(true);
                ok=true;
                break;
            case R.id.stop:
                if(mediaPlayer!=null && mediaPlayer.isPlaying()){
                    mediaPlayer.stop();
                    releaseSource();
                    binding.numberText.setText("00:00"+"/"+timeParse(max));
                }
                break;
            case R.id.prev:
                if(mediaPlayer==null){
                    initPlayer();
                }
                preMusic();
                break;
            case R.id.next:
                if(mediaPlayer==null){
                    initPlayer();
                }
                nextMusic();
                break;
        }
    }

    private void musicPlayer(){// Turn on asynchronous threads 
        new Thread(){
            @Override
            public void run() {
                while(true){
                    if(ok){
                        progress=mediaPlayer.getCurrentPosition();// Get current progress 
                        try {
                            Message msg=Message.obtain();
                            msg.what=100;
                            msg.arg1=progress;
                            handler.sendMessage(msg);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

    private String timeParse(int duration){// The method of converting a point in time into a string 
        String str="";
        int minute=duration/60000;
        int seconds=duration/1000%60;
        if(minute<10){
            str="0"+minute;
        }else{
            str=""+minute;
        }
        if(seconds<10){
            str+=":0"+seconds;
        }else{
            str+=":"+seconds;
        }
        return str;
    }

    //seekbar Monitor 
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        this.progress=progress;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        ok=false;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(this.progress);
        ok=true;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {// Call... When playback is complete 
        nextMusic();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {// Call on error 
        return true;
    }

    private void nextMusic(){// Next music 
        releaseSource();
        if(index<musics.length-1){
            index++;
        }else{
            index=0;
        }
        initPlayer();
        mediaPlayer.start();
        ok=true;
    }

    @SuppressLint("SetTextI18n")
    private void preMusic(){// Last music 
        releaseSource();
        if(index>0){
            index--;
        }else{
            index=musics.length-1;
        }
        initPlayer();
        mediaPlayer.start();
        ok=true;
    }

    private void initPlayer(){// Initialize player 
        mediaPlayer=MediaPlayer.create(this,musics[index]);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);

        max=mediaPlayer.getDuration();// Get playback duration 
        binding.seekBar2.setMax(max);
        binding.numberText.setText("00:00"+"/"+timeParse(max));
        binding.timeText.setText(" The first "+(index+1)+" The first ");

    }

    private void releaseSource(){// Release music player resources 
        ok=false;
        mediaPlayer.release();
        mediaPlayer=null;
        progress=0;
        binding.seekBar2.setProgress(0);
    }
}

copyright notice
author[€ € - flying - ~ £],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262335020896.html

Random recommended