Basic Usage of Android Media Player Audio Player

Keywords: MediaPlayer Android network xml

Get the MediaPlayer instance:
1. MediaPlay mediaPlayer=MediaPlayer.create(this,R.raw.test)
2. MediaPlay mediaPlayer=new MediaPlayer();

Media Player plays files from three main sources:
1. Play the audio files in memory (e.g. the audio files in the raw under the project resource, MediaPlayer.create(this, R.raw.test));
2. Play an audio file (mediaPlayer.setDataSource("/sdcard/test.mp3") under the sd card or other file path;
3. Play the media player from the network. SetDataSource(“ http://www.test.com/music/test.mp3"));

The main control methods of mediaPlayer are:
prepare() and prepareAsync() provide synchronous and asynchronous ways to set the player into the preparedness state. It is important to note that if the MediaPlayer instance is created by the create method, there is no need to call prepare() before the first start of play, because the Create method has already been called.
start() is the way to actually start playing files.
pause() and stop() are relatively simple, playing the role of pausing and stopping play.
seekTo() is a positioning method, which allows the player to play from the specified location. It is important to note that this method is an asynchronous method. That is to say, when this method returns, it does not mean that the positioning is completed, especially the playing network files. When the real positioning is completed, OnSeekComplete () will be triggered, and setOnSeekCompleteListener(OnSeekCompleteListener) can be called if necessary. Listener) Set up a listener to process.
release() can release the resources occupied by the player, and it should be called to release the resources as soon as it is determined that the player will no longer be used.
reset() allows the player to recover from the Error state and return to the Idle state.

Here's a code example:

public class MainActivity extends AppCompatActivity {

    private SeekBar seekBar;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.seekBar);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //Get the position after the drag
                int progress=seekBar.getProgress();
                //Jump to Drag Play
                mediaPlayer.seekTo(progress);

            }
        });
    }

    public void isPlayOrPause(View view){
        final ImageButton imageButton= (ImageButton) view;
        if(mediaPlayer==null){
            //Instantiate MediaPlay
            //Play audio files in applications
            //mediaPlayer = MediaPlayer.create(this, R.raw.roar);

            //Play audio in memory card
            mediaPlayer=new MediaPlayer();
            //Set type
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try{
                //Setting Sound Source (Memory Card)
                mediaPlayer.setDataSource(this, Uri.parse("file://mnt/sdcard/Music/roar.mp3"));
                //Sound Source (Network)
                mediaPlayer.setDataSource(this, Uri.parse("http://192.168.43.135/internet.mp3"));

                //Ready (memory card)
                mediaPlayer.prepare();

                //Prepare (network)
                mediaPlayer.prepareAsync();

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


            //Prepared for completion of the monitoring
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                    //Modify the icon to a paused Icon
                    imageButton.setImageResource(android.R.drawable.ic_media_pause);
                    //Total length of time for music acquisition
                    int duration=mediaPlayer.getDuration();
                    //Set the maximum value of the progress bar to the total length of the music
                    seekBar.setMax(duration);
                    new MyThread().start();
                }
            });

        }else if(mediaPlayer.isPlaying()){
            //Pause playback
            mediaPlayer.pause();
            //Change icon to play icon
            imageButton.setImageResource(android.R.drawable.ic_media_play);
        }else{
            //Start playing audio
            mediaPlayer.start();
            //Modify icon to pause icon
            imageButton.setImageResource(android.R.drawable.ic_media_pause);
        }

    }


    class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            while(seekBar.getProgress()<=seekBar.getMax()){
                //Get the location of the current music play
                int currentPosition=mediaPlayer.getCurrentPosition();
                //Get the progress bar moving
                seekBar.setProgress(currentPosition);
            }
        }
    }


//Here is the layout file (xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="horizontal"
    tools:context="ghq.zking.com.ghq_android_26.MainActivity">

    <SeekBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seekBar" />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_media_play"
        android:onClick="isPlayOrPause"
        />
</LinearLayout>

Posted by leeperryar on Mon, 25 Mar 2019 15:57:29 -0700