8-3 Play Music and Video

1. Play music

1. Use MediaPlayer to play music
Playing audio files in Android is generally implemented using the MediaPlayer class, which provides a very comprehensive control method for audio files in multiple formats, so that the work of playing music becomes very simple. Some of the more commonly used control methods in the MediaPlayer class are listed below.

Let's sort out the workflow of MediaPlayer. First, you need to create a MediaPlayer object, then call the setDataSource() method to set the path of the audio file, then call the prepare() method to make the MediaPlayer enter the ready state, then call the start() method to start playing the audio, and call the pause() method to The playback will be paused, and the reset() method will be called to stop the playback.

layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:textAllCaps="false"/>

</LinearLayout>

logic code

MediaPlayer can be used to play audio from network, local and application installation packages. For the sake of simplicity, let's take the example of playing the audio in the application installation package.

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mBinding;
    MediaPlayer mMediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Initialize ViewBinding
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initMediaPlayer();
        initListener();
    }

    private void initListener() {
        // play
        mBinding.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mMediaPlayer.isPlaying()) {
                    mMediaPlayer.start();
                }
            }
        });

        // pause
        mBinding.pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                }
            }
        });

        // stop
        mBinding.stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.reset();
                    initMediaPlayer();
                }
            }
        });
    }

    private void initMediaPlayer() {
        AssetManager assetManager = getAssets();
        try {
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd("music.mp3");
            mMediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
            mMediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }
}

2. Play the video

1. Use the VideoView class to implement

Playing video files is actually not more complicated than playing audio files, mainly using the VideoView class. This class integrates the display and control of the video, and we can complete a simple video player with the help of it. The usage of VideoView is similar to MediaPlayer, and the common methods are as follows.

The next problem is to store video resources. Unfortunately, VideoView does not support direct playback of video resources in the assets directory, so we can only find other solutions. The res directory allows us to create another raw directory, and resource files such as audio and video can also be placed here, and VideoView can directly play the video resources in this directory.

layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <Button
            android:id="@+id/playVideo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Play"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/pauseVideo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Pause"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/replayVideo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Replay"
            android:textAllCaps="false"/>

    </LinearLayout>

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

logic code

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mBinding;
    MediaPlayer mMediaPlayer = new MediaPlayer();
    private VideoView mVideoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        
        // play video
        playVideo();
    }

    private void playVideo() {
    // Get the uri of the video file in the res directory
        Uri uri = Uri.parse( "android.resource://"  + getApplicationContext().getPackageName() +  "/"  +R.raw.video);
        //Uri uri = Uri.parse("android.resource://$packageName/${R.raw.video}");
        //  val uri = Uri.parse("android.resource://$packageName/${R.raw.video}")

        mVideoView = mBinding.videoView;
        mBinding.videoView.setVideoURI(uri);

        // Start playing
        mBinding.playVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.start();
                }
            }
        });
        // Pause playback
        mBinding.pauseVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                }
            }
        });
        // Replay
        mBinding.replayVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mVideoView.isPlaying()) {
                    mVideoView.resume();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Release the resources occupied by VideoView
        mVideoView.suspend();
    }
}

In this case, you have almost mastered the basic usage of VideoView. However, why is its usage so similar to MediaPlayer? In fact, VideoView just helped us to do a good package, it still uses MediaPlayer to control video files behind it. In addition, it should be noted that VideoView is not a universal video playback tool, and it has major deficiencies in video format support and playback efficiency. Therefore, it is not realistic to write a very powerful video player just using VideoView. But if it's just used to play the title animation of some games, or the video promotion of an application, using VideoView is more than enough.

Effect

Tags: Android Android Studio

Posted by snoopgreen on Mon, 02 May 2022 18:47:42 +0300