Easy Tutorial
❮ Javascript Or And And Css Search Bar ❯

9.2 MediaPlayer Playback of Audio and Video

Category Android Basic Tutorial

Introduction:

>

This section introduces the MediaPlayer in Android's multimedia framework. We can use this API to play audio and video. This class is a crucial component in Android's multimedia framework, allowing us to acquire, decode, and play audio and video with minimal steps. It supports three different media sources:

In this section, we will use MediaPlayer to create a simple example for playing audio and video!

Official API documentation: MediaPlayer


1. Detailed Methods


1) Obtain a MediaPlayer Instance:

You can directly new or call the create method:

MediaPlayer mp = new MediaPlayer();
MediaPlayer mp = MediaPlayer.create(this, R.raw.test);  // No need to call setDataSource

There is also a form of create: create(Context context, Uri uri, SurfaceHolder holder) which creates a media player via Uri and a specified SurfaceHolder [abstract class].


2) Set the Playback File:

// ① Resource in raw:
MediaPlayer.create(this, R.raw.test);

// ② Local file path:
mp.setDataSource("/sdcard/test.mp3");

// ③ Network URL file:
mp.setDataSource("http://www.xxx.com/music/test.mp3");

>

Additionally, setDataSource() has multiple methods, one of which includes a parameter of type FileDescriptor. When using this API, place the file in the assets folder parallel to the res folder and set the DataSource using the following code:

AssetFileDescriptor fileDescriptor = getAssets().openFd("rain.mp3");
m_mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());

3) Other Methods

>


2. Code Example

Example One: Using MediaPlayer to Play Audio:

Running Effect:

Key Code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_play;
    private Button btn_pause;
    private Button btn_stop;
    private MediaPlayer mPlayer = null;
    private boolean isRelease = true;   // Flag to check if MediaPlayer is released

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        btn_play = (Button) findViewById(R.id.btn_play);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_play.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_play:
                if (isRelease) {
                    mPlayer = MediaPlayer.create(this, R.raw.fly);
                    isRelease = false;
                }
                mPlayer.start();   // Start playback
                btn_play.setEnabled(false);
                btn_pause.setEnabled(true);
                btn_stop.setEnabled(true);
                break;
            case R.id.btn_pause:
                mPlayer.pause();     // Pause playback
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(false);
                break;
            case R.id.btn_stop:
                mPlayer.reset();     // Reset MediaPlayer
                mPlayer.release();   // Release MediaPlayer
                isRelease = true;
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(false);
                break;
        }
    }
}

Notes:

>

The audio file is located in the res/raw directory. The MediaPlayer is created using the create method, so there is no need to call prepare() before starting playback for the first time. If created using the constructor, prepare() must be called once! Also, here is an example from the official documentation for playing audio from other sources:

Local Uri:

Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

External URL:

String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();

>

Note: If you stream an online audio file via URL, the file must support progressive download.


Example Two: Using MediaPlayer to Play Video

MediaPlayer is primarily used for playing audio and does not provide a video output interface, so we need to use other components to display the video. This is a Chinese to English translation. Please provide the English translation for this text. Do not provide any explanations or text apart from the translation.

Chinese: 组件来显示MediaPlayer播放的图像输出,我们可以使用用SurfaceView 来显示,下面我们使用SurfaceView来写个视频播放的例子:

运行效果图MediaPlayerDemo.zip

MediaPlayerDemo2.zip

VideoViewDemo.zip


Summary of This Section:

>

In this section, we've briefly introduced how to use MediaPlayer to play audio and combine it with SurfaceView to play videos. We also demonstrated a simple example of using VideoView to play videos. These are very basic usages, and we believe they are easy to learn. Thank you.

-1.0 Android Basic Beginner Tutorial

-1.0.1 2015 Latest Android Basic Beginner Tutorial Contents

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Developing Android Apps with Eclipse + ADT + SDK

-1.2.2 Developing Android Apps with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial: Basic Operations on Local Repository

-1.5.2 Git: Setting Up Remote Repository on GitHub

-1.6 How to Use 9-Patch Images

-1.7 Interface Prototype Design

-1.8 Project Source Analysis (Various Files, Resource Access)

-1.9 Android App Signing and Packaging

-1.11 Decompiling APK to Retrieve Code & Resources

-2.1 Concepts of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 Detailed Explanation of TextView (Text Field)

-2.3.2 Detailed Explanation of EditText (Input Field)

-2.3.3 Button and ImageButton

-2.3.4 ImageView (Image View)

-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton and Switch

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Drag Bar)

-2.3.9 RatingBar (Star Rating Bar)

-2.4.1 ScrollView (Scroll Bar)

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Basic Adapter Explanation

-2.4.5 Simple Usage of ListView

-2.4.6 Optimization of BaseAdapter

-2.4.7 Focus Issues with ListView

-2.4.8 Solving Checkbox Misalignment in ListView

-2.4.9 Data Update Issues with ListView

-2.5.0 Building a Reusable Custom BaseAdapter

-2.5.1 Implementing Multi-Layout ListView Items

-2.5.2 Basic Usage of GridView (Grid View)

-2.5.3 Basic Usage of Spinner (List Option Box)

-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Field)

-2.5.5 Basic Usage of ExpandableListView (Collapsible List)

-2.5.6 Basic Usage of ViewFlipper (Flip View)

-2.5.7 Basic Usage of Toast

-2.5.8 Detailed Explanation of Notification (Status Bar Notification)

-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)

-2.6.0 Basic Usage of Other Common Dialogs

-2.6.1 Basic Usage of PopupWindow (Floating Box)

-2.6.2 Menu (Menu)

-2.6.3 Simple Usage of ViewPager

-2.6.4 Simple Usage of DrawerLayout (Official Side Menu)

-3.1.1 Event Handling Mechanism Based on Listeners

-3.2 Event Handling Mechanism Based on Callbacks

-3.3 Analysis of Handler Message Passing Mechanism

-3.4 TouchListener vs OnTouchEvent + Multi-Touch

-3.5 Listening for Content Changes in EditText

-3.6 Responding to System Setting Changes (Configuration Class)

-3.7 AsyncTask (Asynchronous Task)

-3.8 Gestures (Gestures)

-4.1.1 Beginning with Activity

-4.1.2 Intermediate with Activity

-4.1.3 Advanced with Activity

-4.2.1 Introduction to Service

-4.2.2 Intermediate with Service

-4.2.3 Advanced with Service

-4.3.1 Basic with BroadcastReceiver

-4.3.2 In-Depth with BroadcastReceiver

-4.4.1 Introduction to ContentProvider

-4.4.2 In-Depth with ContentProvider – Document Provider

WeChat Subscription

❮ Javascript Or And And Css Search Bar ❯