Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods of VideoView
3.
MediaController in VideoView
4.
Example of VideoView
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Android VideoView

Author Rahul Sain
2 upvotes
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A video file is displayed using VideoView. It can import thumbnails from various sources (such as content providers or resources), determine its size from the video so that any layout manager can utilize it, and offer display choices such as scaling and tinting.

In this article, we will learn about VideoView in Android. But before jumping into this, we would strongly recommend learning about WebView.

The upcoming section will discuss various methods provided by VideoView for displaying video or playing audio files with the help of some examples.

Methods of VideoView

VideoView may play videos from resource files, local data, or URLs.

Let's look at some methods provided by the VideoView for playing and controlling the video player.

  1. setMediaController(MediaController mediaController): This VideoView function is used to configure the controller for video playback controls.
  2. setVideoURI(Uri URI)This function is used to specify the absolute path of the video file that will be played.
  3. start()This VideoView function is used to begin the playback of a video file.
  4. stopPlayback()This function is used to stop the track playback.
  5. pause()This video view method pauses the current playback.
  6. isPlaying()This technique determines whether or not a video is currently playing. This technique produces a Boolean result. If the video is playing, it returns true; otherwise, it returns false.
  7. resume(): This method resumes the playback.
  8. seekTo(int milliseconds): This method places the current playing video to the supplied time in milliseconds.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

MediaController in VideoView

A MediaController class is used to offer controls for video playback. If a video is merely played using the VideoView class, the user has no control over the video's playback, which will continue until the film's conclusion is reached. This problem can be solved by connecting a MediaController instance to the VideoView instance.

The Media Controller will then present the user with a range of controls for managing playback (seeking backward/forward and pausing in the video timeline).

Let's head over to some of the most effective methods of the MediaController class that are used to control playing.

  1. setAnchorView(View view): setAnchorView specifies the view to which the controller will be anchored. This determines where the controls appear on the screen.
  2. show(): This function shows the controller on the screen.
  3. show(int timeout): This function sets the time to show the controller on the screen.
  4. hide(): This technique is used to hide the controls from view on the screen.
  5. isShowing(): This function returns a Boolean value indicating whether or not the controls are visible to the user at the time.

For more information, head out to official documentation to read about more methods and use cases in detail.

Example of VideoView

The following is an example of a VideoView in Android. We play a video in a video view using a Media Controller and execute set on error and completion listener events and show Toast when the video is done, or an issue occurs while playing the video.

The changed main activity file MainActivity.kt is shown below.

Code:

package com.codingninjas.ui

import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    var button: Button? = null
    var editText: EditText? = null
    var videoView: VideoView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById<View>(R.id.btn) as Button
        editText = findViewById<View>(R.id.eT) as EditText
        videoView = findViewById<View>(R.id.vV) as VideoView
        button!!.setOnClickListener {
            val url = editText!!.text.toString()
            val mediaController = MediaController(this)
            mediaController.setAnchorView(videoView)
            val uri: Uri = Uri.parse(url)
            videoView!!.setMediaController(mediaController)
            videoView!!.setVideoURI(uri)
            videoView!!.requestFocus()
            videoView!!.start()

            videoView!!.setOnCompletionListener(OnCompletionListener {
                Toast.makeText(applicationContext, "Thanks for Watching!", Toast.LENGTH_SHORT)
                    .show()
            })
            videoView!!.setOnErrorListener(MediaPlayer.OnErrorListener { mp, what, extra ->
                Toast.makeText(
                    applicationContext,
                    "Can't Play Video",
                    Toast.LENGTH_SHORT
                ).show()
                false
            })
        }
    }
}

In this step, we open MainActivity and add the code to start the video view and a MediaController object to control the video playback.

In this class, we also establish the URI for the video, execute set on error and completion listener events, and show a Toast message when the movie is finished, or an error occurs while playing it.

Our main_activity.xml looks like the code snippet given below.

Code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="8dp"
    android:paddingTop="8dp"
    android:paddingRight="8dp"
    android:paddingBottom="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="VideoView"
        android:textSize="35sp" />

    <EditText
        android:id="@+id/eT"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp"
        android:focusable="true"
        android:hint="Enter URL"
        android:importantForAutofill="auto"
        android:inputType="text"
        android:text="https://download.samplelib.com/mp4/sample-5s.mp4"
        android:textColorHighlight="#FD8EB4"
        android:textColorHint="#FF5252" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/eT"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/eT"
        android:text="Enter" />

    <VideoView
        android:id="@+id/vV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

And finally, we will use internet permission in our AndroidManifest.xml file to load URLs through the internet.

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codingninjas.ui">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.UI">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output:

                    

When you launch the app, you will see a video playing while the app opens. When you click on the Video button, the Media Controller will display on the screen.

We will pass the URL of the mp4 video, and it will load and start playing it as soon as you press enter.

It will also render the Media Controller class for changing seek a position within the video or changing its speed. For that, you have to create your own Custom Class. We have set a video completion listener which will print Thanks for Watching! toast when the video is completed. Also, we have employed a video error listener which will be called when the URL is incorrect or the video can’t be played due to mismatch extension support or defective video. It will print Can't Play Video toast when this listener is called.

FAQs

  1. How do I mute video on Android?
    Ans: If you want to access the MediaPlayer of a VideoView, you must use MediaPlayer. MediaPlayer and OnPreparedListener. Then, in OnCompletionListener, you can invoke MediaPlayer. To set the volume to 0, use the setVolume(0f, 0f) method.
     
  2. How do I get raw videos on Android?
    Ans: Place the video in your project's res/raw folder. Make a raw folder in the res folder. It must be in a supported format (MP4, 3GP, WMV) and labeled with lower case numbers, underscores, and dots in the filename, for example, video_file_360p.mp4.
     
  3. What is an ExoPlayer?
    Ans: ExoPlayer is an app-level media player built on Android's low-level media APIs. ExoPlayer has several advantages over Android's built-in MediaPlayer. Many of the similar media formats as MediaPlayer are supported and adaptive formats such as DASH and SmoothStreaming.

Key Takeaways

In this article, we have extensively discussed VideoView in Android and its essential methods.

You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.

We hope that this blog has helped you enhance your knowledge regarding VideoView and if you would like to learn more, check out our articles on SearchView. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Android WebView
Next article
Android SearchView
Live masterclass