Android makes simple music player and video player

Make simple music player and video player

play multimedia files

  • Android has done a very good support in playing audio and video, it provides a very complete set of API, so that developers can easily write a simple audio or video player

play audio

  • Playing audio files in Android is generally implemented using the MediaPlayer class. It provides a very comprehensive control method for audio files in various formats, so that the work of playing music becomes very simple. The following table lists some of the MediaPlayer classes. more commonly used method

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-wnKJobu4-1671707953702)(C:/Users/zhengbo/%E6%88%91%E7%9A%84 %E5%AD%A6%E4%B9%A0/Typora%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E5%AE%89%E5%8D% 93/image-20221222164558552.png)]

Workflow of MediaPlayer

  • First, you need to create a MediaPlayer object, then call the setDataSource() method to set the playback path of the audio file, and then call the prepare() method to make the MediaPlayer enter the ready state.
  • Next, call the start() method to start playing the audio, then call the pause() method to pause, and call the reset() method to stop playing.

project example

  • Create a new PlayAudioTest project, and then modify the code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

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

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


</LinearLayout>
  • Three buttons are defined to represent play, pause and stop
  • MediaPlayer can be used to play the audio in the network, local and application installation package. The following example plays the audio in the application installation package.
  • AS allows us to create an assets directory in the project project, and store any files and subdirectories under this directory. These files and subdirectories will be packaged into the installation file when the project is packaged, and then we can use it in the program. The interface provided by the AssetManager class reads the files in the assets directory.
  • Create an assets directory below. This directory must be created under the app/src/main directory, which is the same level as the java and res directories. Right-click app/src/main->new->Directory, and then Enter "assets" in the pop-up dialog box, and the directory will be created.
  • Then prepare an audio resource and put it under this directory.
  • Then modify the code logic in MainActivity
package com.zb.playaudiotest

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    
    
    private val mediaPlayer = MediaPlayer()
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initMediaPlayer()
        play.setOnClickListener {
    
    
            if (!mediaPlayer.isPlaying) {
    
    
                mediaPlayer.start() //开始播放
            }
        }
        pause.setOnClickListener {
    
    
            if (mediaPlayer.isPlaying) {
    
    
                mediaPlayer.pause() //暂停播放
            }
        }
        stop.setOnClickListener {
    
    
            if (mediaPlayer.isPlaying) {
    
    
                mediaPlayer.reset() //停止播放
                initMediaPlayer()
            }
        }
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
    }


    /**
     * 为mediaPlayer对象进行初始化
     */
    private fun initMediaPlayer() {
    
    
        val assetManager = assets
        val fd = assetManager.openFd("music.mp3")
        mediaPlayer.setDataSource(fd)
        mediaPlayer.prepare()
    }
}
  • When the class is initialized, create an instance of MediaPlayer, and then call the initMediaPlayer() method in the onCreat() method to initialize the MediaPlayer object
  • In the initMediaPlayer() method, first obtain an instance of AssetManager through the getAssets() method. Assmanager can be used to read any resources in the assets directory, and then call the opedFd() method to open the audio file handle, and then call setDataSource( ) method and prepare() method to prepare the mediaPlayer for playback.
  • Then there are the click events of each button, corresponding to simple start, pause, and stop logic
  • Finally, in the onDestroy() method, we also need to call the stop() method and the release() method respectively to release the resources related to MediaPlayer.
  • Such a simple music player is completed.

play video

  • Playing videos is mainly implemented using the VideoView class. This class integrates video display and control. We can complete a simple video player only with it. The usage of VideoView is similar to that of MediaPlayer. Common methods are shown in the following table

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-zo6MytSJ-1671707953704)(C:/Users/zhengbo/%E6%88%91%E7%9A%84 %E5%AD%A6%E4%B9%A0/Typora%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E5%AE%89%E5%8D% 93/image-20221222174632519.png)]

project example

  • Create a new PlayVideoTest project, and then modify the code in the activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="play" />

        <Button
            android:id="@+id/pause"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="pause" />

        <Button
            android:id="@+id/replay"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="replay" />
    </LinearLayout>

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


</LinearLayout>
  • In this layout file, three buttons are also placed, which are used to control the playback, pause, and replay of the video. In addition, a VideoView is placed under the button, and the later video will be displayed in this place.
  • Next is the problem of storing 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, where files such as video and audio can also be stored, and VideoView can directly play video resources in this directory.
  • Right-click app/src/main/res->New->Directory, enter "raw" in the pop-up dialog box, complete the creation of the raw directory, and put the video resources to be played in it. It should be noted that There cannot be capital letters in the file name stored under raw, otherwise it will become popular.
  • Then modify the code in MainActivity
package com.zb.playvideotest

import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val uri = Uri.parse("android.resource://$packageName/${
      
      R.raw.video}")
        videoView.setVideoURI(uri)
        play.setOnClickListener {
    
    
            if (!videoView.isPlaying) {
    
    
                videoView.start() //开始播放
            }
        }
        pause.setOnClickListener {
    
    
            if (videoView.isPlaying) {
    
    
                videoView.pause() //暂停播放
            }
        }
        replay.setOnClickListener {
    
    
            if (videoView.isPlaying) {
    
    
                videoView.resume() //重新播放
            }
        }
    }

    override fun onDestroy() {
    
    
        super.onDestroy()
        videoView.suspend()
    }
}
  • In the onCreat() method, the Uri.parse() method is called to parse the video.map file in the raw directory into a Uri object. The writing method used here is the fixed writing method required by Android.
  • Then call the setVideoURI() method of VideoView to pass in the Uri object just parsed, so that the initialization of VideoView is completed.
  • Then there is the click event of each button, and finally, the suspend() method of a videoView is called in the onDestory() method to release the resources occupied by the VideoView.
  • Such a simple video player is created

Guess you like

Origin blog.csdn.net/weixin_45809829/article/details/128412537