Play video from url in VideoView [Android]
Asked Answered
J

8

27

I found a similar questions but nothing work for me. I try play video from this url:

http://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4

My java code:

VideoView videoView= (VideoView)findViewById(R.id.exerciseVideo);
    Uri uri = Uri.parse(TEST_URL);
    videoView.setVideoURI(uri);
    videoView.requestFocus();
    videoView.start();

When I run app nothing is displayed in activity and IDE does not show any errors. ANy idea, please?

EDIT:

My activity where I want to show video:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 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="com.example.martin.fitnessapp.ExerciseDetailActivity"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:weightSum="2">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/exerciseImgA"
                android:layout_weight="1"
                android:scaleType="fitCenter"
                android:adjustViewBounds="true"
                android:paddingRight="8dp"/>

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/exerciseImgB"
                android:layout_weight="1"
                android:scaleType="fitCenter"
                android:adjustViewBounds="true"
                android:paddingLeft="8dp"/>
        </LinearLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text=""
            android:id="@+id/exerciseDesc" />

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

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/guideImg"
            android:scaleType="fitCenter"
            android:adjustViewBounds="true"/>


    </LinearLayout>
</ScrollView>
Jammie answered 4/11, 2016 at 23:46 Comment(4)
Did you read logcat to see if it has any explanation? Did you confirm that the device can even go to that url? Are you sure its not session protected and non-public?Envoi
I've tried another one online and one video from local ... no one worksJammie
confirm by going that url on your browser ON THE DEVICE to confirm what the behavior is. You need to see if its even a valid URL that you can access in a previously un-authed session. Don't assume just because it load on the web that it'll load for you, sessions make a big difference.Envoi
in browser works fine.Jammie
C
48

Try this code.. This code works perfectly for me..

VideoView videoView = findViewById(R.id.videoView);
videoView.setVideoPath("http://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4");
videoView.start();
Clarissa answered 5/11, 2016 at 6:15 Comment(9)
I add your code and still not works :/ pastebin.com/gGej1GR0 ... I edit my post and add current layout .. It may helps to solve itJammie
It is not allowing youtube links to play! Error states like "Can't play this video."Peppy
@Peppy if u want to play a youtube video, u can check this pierfrancescosoffritti.github.io/android-youtube-playerMizzle
@Peppy You can use Youtube Android Player Api. Check out developers.google.com/youtube/android/playerClarissa
@subratasharma yes, i used that one after googling, thanks!Peppy
@subratasharma yes, i used that one after googling, thanks!Peppy
saying "can't play this video"Walloping
Wow, Android-Youtube-Player worked like charm. Thx Lots @subratasharmaFlagstad
just change http to https in the same url and it will start working.Kutzer
B
9

For me, changing the URL from

"http://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4"

to:

"https://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4"

made it work.

In other words, I used HTTPS instead of HTTP.

I used the following code to start the video:

final VideoView videoView = findViewById(R.id.videoview); //id in your xml file
videoView.setVideoURI(Uri.parse(URL)); //the string of the URL mentioned above
videoView.requestFocus();
videoView.start();
Beluga answered 10/1, 2021 at 20:55 Comment(2)
This should be the top voted answer. I got hamstrung on this for a whole day!Maximilian
yes changing from http to https worked for the same URL.Kutzer
M
4

As I know you shouldn't use wrap_content for VideoView height. VideoView didn't resize itself after video cached

Monoplegia answered 12/1, 2018 at 12:0 Comment(0)
L
3

Kindly add Internet permission them Change layout_height wrap_content into match parent. this is a code for this problem

public class MainActivity extends Activity {
    private ProgressDialog bar;
    private String path="https://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4";
    private MediaController ctlr;
    private VideoView videoView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_main);
      bar=new ProgressDialog(MainActivity.this);
        bar.setTitle("Connecting server");
        bar.setMessage("Please Wait... ");
        bar.setCancelable(false);
        bar.show();
       if(bar.isShowing()) {
           videoView = findViewById(R.id.v1);
           Uri uri = Uri.parse(path);
           videoView.setVideoURI(uri);
           videoView.start();
           ctlr = new MediaController(this);
           ctlr.setMediaPlayer(videoView);
           videoView.setMediaController(ctlr);
           videoView.requestFocus();
       }
        bar.dismiss();
    }
}
Lightly answered 13/7, 2018 at 7:27 Comment(0)
D
2
videoView.setURI(Uri.parse(url));// use methods to set url
videoView.start();

then accept permission

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Dinge answered 5/6, 2020 at 14:19 Comment(1)
ohh! I was trying to play from internet without permissions. Thank you!Glyptodont
I
0
public class ShowVideoActivity extends AppCompatActivity {
    private static final String VIDEO_SAMPLE =
            "https://www.youtube.com/watch?v=HexFqifusOk&list=RDHexFqifusOk&start_radio=1";
    private VideoView mVideoView;
    private TextView mBufferingTextView;
    // Current playback position (in milliseconds).
    private int mCurrentPosition = 0;
    // Tag for the instance state bundle.
    private static final String PLAYBACK_TIME = "play_time";

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

        mVideoView = findViewById(R.id.videoview);
        mBufferingTextView = findViewById(R.id.buffering_textview);

        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
        }

        // Set up the media controller widget and attach it to the video view.
        MediaController controller = new MediaController(this);
        controller.setMediaPlayer(mVideoView);
        mVideoView.setMediaController(controller);
    }


    @Override
    protected void onStart() {
        super.onStart();

        // Load the media each time onStart() is called.
        initializePlayer();
    }

    @Override
    protected void onPause() {
        super.onPause();

        // In Android versions less than N (7.0, API 24), onPause() is the
        // end of the visual lifecycle of the app.  Pausing the video here
        // prevents the sound from continuing to play even after the app
        // disappears.
        //
        // This is not a problem for more recent versions of Android because
        // onStop() is now the end of the visual lifecycle, and that is where
        // most of the app teardown should take place.
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mVideoView.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        // Media playback takes a lot of resources, so everything should be
        // stopped and released at this time.
        releasePlayer();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save the current playback position (in milliseconds) to the
        // instance state bundle.
        outState.putInt(PLAYBACK_TIME, mVideoView.getCurrentPosition());
    }

    private void initializePlayer() {
        // Show the "Buffering..." message while the video loads.
        mBufferingTextView.setVisibility(VideoView.VISIBLE);

        // Buffer and decode the video sample.
        Uri videoUri = getMedia(VIDEO_SAMPLE);
        mVideoView.setVideoURI(videoUri);

        // Listener for onPrepared() event (runs after the media is prepared).
        mVideoView.setOnPreparedListener(
                new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {

                        // Hide buffering message.
                        mBufferingTextView.setVisibility(VideoView.INVISIBLE);

                        // Restore saved position, if available.
                        if (mCurrentPosition > 0) {
                            mVideoView.seekTo(mCurrentPosition);
                        } else {
                            // Skipping to 1 shows the first frame of the video.
                            mVideoView.seekTo(1);
                        }

                        // Start playing!
                        mVideoView.start();
                    }
                });

        // Listener for onCompletion() event (runs after media has finished
        // playing).
        mVideoView.setOnCompletionListener(
                new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        Toast.makeText(ShowVideoActivity.this,
                                "Completed",
                                Toast.LENGTH_SHORT).show();

                        // Return the video position to the start.
                        mVideoView.seekTo(0);
                    }
                });
    }


    // Release all media-related resources. In a more complicated app this
    // might involve unregistering listeners or releasing audio focus.
    private void releasePlayer() {
        mVideoView.stopPlayback();
    }

    // Get a Uri for the media sample regardless of whether that sample is
    // embedded in the app resources or available on the internet.
    private Uri getMedia(String mediaName) {
        if (URLUtil.isValidUrl(mediaName)) {
            // Media name is an external URL.
            return Uri.parse(mediaName);
        } else {

            // you can also put a video file in raw package and get file from there as shown below

            return Uri.parse("android.resource://" + getPackageName() +
                    "/raw/" + mediaName);


        }
    }

}
Incomprehensive answered 16/3, 2021 at 6:2 Comment(1)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Tallboy
M
0

at the first you need to set internet permission in the AndroidManifest.xml file like below:

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

and then for playing video from url in android use the below structure for more readable I commented the code:)

    // Your Video URL
    String videoUrl = "https://videocdn.bodybuilding.com/video/mp4/62000/62792m.mp4";

    // on below line we are initializing our variables.
    videoView = findViewById(R.id.videoView);


    // Uri object to refer the
    // resource from the videoUrl
    Uri uri = Uri.parse(videoUrl);

    // sets the resource from the
    // videoUrl to the videoView
    videoView.setVideoURI(uri);

    // creating object of
    // media controller class
    MediaController mediaController = new MediaController(this);

    // sets the anchor view
    // anchor view for the videoView
    mediaController.setAnchorView(videoView);

    // sets the media player to the videoView
    mediaController.setMediaPlayer(videoView);

    // sets the media controller to the videoView
    videoView.setMediaController(mediaController);

    // starts the video
    videoView.start();
Manageable answered 26/9, 2023 at 18:52 Comment(0)
N
0

Your code will only work for videos from local storage

VideoView videoView= (VideoView)findViewById(R.id.exerciseVideo);
Uri uri = Uri.parse(TEST_URL);
videoView.setVideoURI(uri);
videoView.start();

If you want to play video from the network. You need this

VideoView videoView = (VideoView)findViewById(R.id.exerciseVideo);
videoView.setVideoPath(TEST_URL);  // TEST_URL should start with http or https or other network protocol
videoView.start();

If only https urls are working. Add this line in manifest inside <application/> tag to enable http url support.

android:usesCleartextTraffic="true"

Remember to check in the manifest for internet permission. Add this if not added in manifest

<uses-permission android:name="android.permission.INTERNET"/>
Norean answered 26/1 at 3:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.