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:
Local resources
Internal URIs, such as those obtained through ContentResolver
External URLs (streams) For a list of media formats supported by Android, see: Supported Media Formats
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
>
getCurrentPosition(): Get the current playback position
getDuration(): Get the duration of the file
getVideoHeight(): Get the video height
getVideoWidth(): Get the video width
isLooping(): Check if looping playback
isPlaying(): Check if currently playing
pause(): Pause
prepare(): Prepare (synchronous)
prepareAsync(): Prepare (asynchronous)
release(): Release the MediaPlayer object
reset(): Reset the MediaPlayer object
seekTo(int msec): Specify the playback position (in milliseconds)
setAudioStreamType(int streamtype): Specify the type of streaming media
setDisplay(SurfaceHolder sh): Set the SurfaceHolder to display multimedia
setLooping(boolean looping): Set whether to loop playback
setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener): Network streaming buffer listener
setOnCompletionListener(MediaPlayer.OnCompletionListener listener): Network streaming end listener
setOnErrorListener(MediaPlayer.OnErrorListener listener): Set error message listener
setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener): Video size listener
setScreenOnWhilePlaying(boolean screenOn): Set whether to use SurfaceHolder for display
setVolume(float leftVolume, float rightVolume): Set volume
start(): Start playback
stop(): Stop playback
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
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.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress 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.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.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)
-4.1.1 Beginning with Activity
-4.1.2 Intermediate with Activity
-4.2.1 Introduction to Service
-4.2.2 Intermediate 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
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Basic Overview of Fragment
- 5.2.1 Fragment Example Walkthrough - Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Walkthrough - Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Walkthrough - Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Walkthrough - Bottom Navigation Bar + ViewPager Swipe to Switch Pages
- 5.2.5 Fragment Example Walkthrough - Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access - File Storage and Reading/Writing
- 6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access - Introduction to SQLite Database
- 6.3.2 Data Storage and Access - Further Exploration of SQLite Database
- 7.1.1 Android Network Programming Essentials and Learning HTTP Protocol
- 7.1.2 Learning Android HTTP Request Headers and Response Headers
- 7.1.3 Android HTTP Request Methods: HttpURLConnection
- 7.1.4 Android HTTP Request Methods: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 Basic Usage of WebView (Web View)
- 7.5.2 Basic Interaction Between WebView and JavaScript
- 7.5.3 Important Considerations for WebView in Android 4.4 and Later
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Error Code Information from Web Pages
- 7.6.1 Network Basics Preparation for Socket Learning
- 7.6.2 Socket Communication Based on TCP Protocol (1)
- 7.6.3 Socket Communication Based on TCP Protocol (2)
- 7.6.4 Socket Communication Based on UDP Protocol
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Comprehensive Analysis of Bitmap (Bitmap) Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Practical Examples of Drawing Classes
- 8.3.3 Paint API - MaskFilter (Mask)
- 8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API - ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API - ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API - ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API - PathEffect (Path Effect)
- 8.3.13 Paint API - Shader (Image Rendering)
- 8.3.14 Paint Enumeration/Constant Values and ShadowLayer Shadow Effects
- 8.3.15 Paint API - Typeface (Font Style)
- 8.3.16 Detailed Explanation of Canvas API (Part 1)
- 8.3.17 Detailed Explanation of Canvas API (Part 2) Clipping Methods Collection
- 8.3.18 Detailed Explanation of Canvas API (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Frame Animation in Android Animation Collection
- 8.4.2 Tween Animation in Android Animation Collection
- 8.4.3 Property Animation in Android Animation Collection - Introduction
- 8.4.4 Property Animation in Android Animation Collection - Further Exploration
- 9.1 Playing Sound Effects with SoundPool (Duang~)
- 9.2 MediaPlayer for Playing Audio and Video
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord for Recording
- 10.1 TelephonyManager (Telephony Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Topic (1) - Introduction
- 10.11 Sensor Topic (2) - Orientation Sensor
- 10.12 Sensor Topic (3) - Accelerometer/Gyroscope Sensor
- 10.12 Sensor Special Topic (4) – Understanding Other Sensors
11.0 Completion of the Latest Android Basic Beginner's Tutorial 2015
12.2 DrySister's Girl Watching App (Version 1) – 2. Parsing Backend Data
12.4 DrySister's Girl Watching App (Version 1) – 4. Adding Data Caching (Incorporating SQLite)