Skip to main content

Android MediaPlayer and VideoView Tutorial


1- MediaPlayer
2- VideoView
3- MediaPlayer example
4- Playing a video with VideoView exampleVideoView is a custommized component which is available of Android, it is the combination of MediaPlayer and SuffaceView which  help you to play a video more easily.
When using VideoView, you can use MediaController, this is available in Android which used to control media (such as start, stop, rewind, pause...)
IF you locate  VideoView and  MediaController in a  FrameLayout, you can get interface as follow:

3- MediaPlayer example

The following simple example, use Media Player to play a music file and some controls of the play such as play, pause, rewind.
Create a project named MediaPlayerTutorial:



4- Playing a video with VideoView example

Now, we can see an example with  VideoView and MediaController located on the surface of the video. You can preview images in following example:
Create a Project named AndroidVideoView:
Create raw folder to store video files.
Copy & Paste video files to raw folder:
Design the Interface:
Drag  VideoView to the Center of  FrameView
Note that  FrameLayout have only a cell to contain all subview, 9 subarea that you see ebove just are 9 gravity areas.
activity_main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    tools:context="org.o7planning.androidvideoview.MainActivity">
 
    <VideoView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/videoView"
        android:layout_gravity="center" />
 
</FrameLayout>
MainActivity.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package org.o7planning.androidvideoview;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;
 
public class MainActivity extends AppCompatActivity {
 
 
    private VideoView videoView;
    private int position = 0;
    private MediaController mediaController;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        videoView = (VideoView) findViewById(R.id.videoView);
 
        // Set the media controller buttons
        if (mediaController == null) {
            mediaController = new MediaController(MainActivity.this);
 
            // Set the videoView that acts as the anchor for the MediaController.
            mediaController.setAnchorView(videoView);
 
 
            // Set MediaController for VideoView
            videoView.setMediaController(mediaController);
        }
 
 
        try {
            // ID of video file.
            int id = this.getRawResIdByName("myvideo");
            videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + id));
 
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
 
        videoView.requestFocus();
 
 
        // When the video file ready for playback.
        videoView.setOnPreparedListener(new OnPreparedListener() {
 
            public void onPrepared(MediaPlayer mediaPlayer) {
 
 
                videoView.seekTo(position);
                if (position == 0) {
                    videoView.start();
                }
 
                // When video Screen change size.
                mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
 
                        // Re-Set the videoView that acts as the anchor for the MediaController
                        mediaController.setAnchorView(videoView);
                    }
                });
            }
        });
 
    }
 
    // Find ID corresponding to the name of the resource (in the directory raw).
    public int getRawResIdByName(String resName) {
        String pkgName = this.getPackageName();
        // Return 0 if not found.
        int resID = this.getResources().getIdentifier(resName, "raw", pkgName);
        Log.i("AndroidVideoView", "Res Name: " + resName + "==> Res ID = " + resID);
        return resID;
    }
 
 
    // When you change direction of phone, this method will be called.
    // It store the state of video (Current position)
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
 
        // Store current position.
        savedInstanceState.putInt("CurrentPosition", videoView.getCurrentPosition());
        videoView.pause();
    }
 
 
    // After rotating the phone. This method is called.
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
 
        // Get saved position.
        position = savedInstanceState.getInt("CurrentPosition");
        videoView.seekTo(position);
    }
 
}
Running apps:
Some note to the code:
Imagine when you use  setAnchorView() to attach  MediaController to  VideoView:
Playing Video from URL:
First, you must declare permission to access Internet  ( android.permission.INTERNET) in  AndroidManifest.xml:
AndroidManifest.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
   package="org.o7planning.androidvideoview">
 
   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
 
   <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
 
 
 
       <activity android:name=".MainActivity">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
 
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
 
</manifest>
Java Code:
?
1
2
3
4
5
6
7
8
9
10
11
// Way 1:
 
Uri video = Uri.parse(videoUrl);
videoView.setVideoURI(video);
 
 
// Way 2:
 
videoView.setVideoPath(video);

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap th...