HI
i want to play a .3GP video file in android phone. i tried below code but it shows cant play video.so please tell me what i will do
This is my code
public class VideoPlay extends Activity {
private String path ;
private VideoView mVideoView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.videoplay);
path="http://www.boodang.com/api/videobb/101009_Pure.3gp";
mVideoView = (VideoView) findViewById(R.id.video);
if (path == "") {
// Tell the user to provide a media file URL/path.
Toast.makeText(
VideoPlay.this,
"Please edit VideoViewDemo Activity, and set path"
+ " variable to your media file URL/path",
Toast.LENGTH_LONG).show();
} else {
/*
* Alternatively,for streaming media you can use
* mVideoView.setVideoURI(Uri.parse(URLstring));
*/
mVideoView.setVideoPath(path);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
}
}
The XML layout is
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="#+id/video"
android:layout_width="320px"
android:layout_height="240px">
</VideoView>
</FrameLayout>
Check the following code which is there in the Android SDK demo
package com.example.android.apis.media;
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoViewDemo extends Activity {
/**
* TODO: Set the path variable to a streaming video URL or a local media
* file path.
*/
private String path = "";
private VideoView mVideoView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.surface_view);
if (path == "") {
// Tell the user to provide a media file URL/path.
Toast.makeText(
VideoViewDemo.this,
"Please edit VideoViewDemo Activity, and set path"
+ " variable to your media file URL/path",
Toast.LENGTH_LONG).show();
} else {
/*
* Alternatively,for streaming media you can use
* mVideoView.setVideoURI(Uri.parse(URLstring));
*/
mVideoView.setVideoPath(path);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
}
}
videoview.xml
<VideoView
android:id="#+id/surface_view"
android:layout_width="320px"
android:layout_height="240px"
/>
This article provides code similar to your sample, though there are some differences, especially with video.start and your sample completely missing MediaController.show.
I suggest cleaning up your code a bit and try the suggestions found in the mentioned article. There's also some good feedback in the article discussions.
As #Peter Lillevold suggests, you should try a reference implementation of a video player first. Here are some links:
Audio and Video
MediaPlayer Documentation
Android VideoView Example
Try these players with a known working video file, there is a link to some in this post. If you implement a player, and these reference videos work, but your .3gp video does not, then the problem may be that the video file itself is not encoded to standards.
Related
I use the code below to play a video from my SD-Card using Video View of Android. I placed a video file named Video.mp4 in the external storage root directory. But when starting my App on my Smartphone and switching to my video activity with the code below for Video.java I see a notification with an OK button saying that the video can not be played. (German: "Video kann nicht wiedergegeben werden.")
Is it a missing permission in my AndroidManifest.xml?
Thanks in advance for any hints and help.
package com.noureddine_ouertani.www.wocelli50;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.MediaController;
import android.widget.VideoView;
public class Video extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
VideoView v = (VideoView) findViewById(R.id.videoView);
v.setVideoURI(Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Video.mp4"));
//Set media controller buttons
v.setMediaController(new MediaController(this));
v.requestFocus();
v.start(); //start Playback
}
}
EDIT:
#Alexandre Martin: Thanks for your answer. I have no general problem with embedding videos in my app. When I create a raw folder and put the video testvideo.mp4 in it then replace
v.setVideoURI(Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Video.mp4"));
with
v.setVideoURI(Uri.parse("android.resource://com.noureddine_ouertani.www.wocelli50/"+ R.raw.testvideo));
in my code, everything works fine and I see my video playing in my app.
Remark: I had to rename Video.mp4 to testvideo.mp4 because capital letters are not allowed for videos called from the raw folder.
My problem is just to get the path to the video on my SD-card.
#Lonnie Zamora: Thanks for your answer. It doesn´t seem to be a format or coding problem. testvideo.mp4 is just Video.mp4 renamed and placed in my raw folder. And it plays fine with the code below:
package com.noureddine_ouertani.www.wocelli50;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.MediaController;
import android.widget.VideoView;
public class Video extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
VideoView v = (VideoView) findViewById(R.id.videoView);
v.setVideoURI(Uri.parse("android.resource://com.noureddine_ouertani.www.wocelli50/"+ R.raw.testvideo));
//Set media controller buttons
v.setMediaController(new MediaController(this));
v.requestFocus();
v.start(); //start Playback
}
}
#CommonsWare: Thanks for your answer. I tried your suggestion but it didn´t solve the problem.
Best regards,
EDIT 2: #CommonsWare It doesn´t seem to be a missing permission or a missing permission request issue. I implemented the following runtime permission logic and see "Video is playing. No permissioon request was needed." which means to me that (Manifest.permission.READ_EXTERNAL_STORAGE == PackageManager.PERMISSION_GRANTED) was true
package com.noureddine_ouertani.www.wocelli50;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class Video extends AppCompatActivity {
final int REQUEST_READ_EXTERNAL_STORAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(getApplicationContext(), "Show explanation for requesting the permission to read the SD-card.", Toast.LENGTH_SHORT).show();
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
Toast.makeText(getApplicationContext(), "No explanation needed, we can request the permission.", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
playmyvideo();
Toast.makeText(getApplicationContext(), "Video is playing. No permissioon request was needed.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
playmyvideo();
Toast.makeText(getApplicationContext(), "Video is playing after permissioon was granted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "permission denied,Disable the functionality that depends on this permission.", Toast.LENGTH_SHORT).show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void playmyvideo(){
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
VideoView v = (VideoView) findViewById(R.id.videoView);
v.setVideoURI(Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/testvideo.mp4"));
//v.setVideoURI(Uri.parse("android.resource://com.noureddine_ouertani.www.wocelli50/"+ R.raw.testvideo));
v.setMediaController(new MediaController(this));
v.requestFocus();
v.start(); //start Playback
}
}
Replace
Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Video.mp4")
(which is invalid, since it lacks a scheme)
with:
Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "Video.mp4"))
SOLUTION #all
Solution to access the external SD-card:
v.setVideoURI(Uri.parse("/storage/sdcard1/testvideo.mp4"));
instead of
v.setVideoURI(Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/testvideo.mp4"));
REASON:
Environment.getExternalStorageDirectory().getPath() == "/storage/emulated/0"
Environment.getExternalStorageDirectory().getPath() delivers the path to an internal storage chip on my smartphone (HUAWEI P8) that is mounted like an SD-card but is not the external SD-card though.
I'm using the library Vitamio to play rtsp live stream. I tried to run the demo videoview class play rtsp link as follows:
http://117.103.224.75:1935/live/definst/VTCHD3/VTCHD3_840x480_1200kbps.stream/playlist.m3u8
==> Result : it run but quality very bad, load videos very low and picture in video are not sharp and sound are not heard. I don't know what to do to make it run smooth and picture is sharp. Please help me this problem ! Thank very much !
this is my code :
private String path="http://117.103.224.75:1935/live/_definst_/VTCHD3/VTCHD3_840x480_1200kbps.stream/playlist.m3u8";
private ProgressDialog prodlg;
private VideoView mVideoView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (!LibsChecker.checkVitamioLibs(this))
return;
setContentView(R.layout.videoview);
prodlg=new ProgressDialog(this);
prodlg.setIcon(R.drawable.ic_launcher);
prodlg.setMessage("wating...");
prodlg.show();
mVideoView = (VideoView) findViewById(R.id.surface_view);
if (path == "") {
// Tell the user to provide a media file URL/path.
Toast.makeText(VideoViewDemo.this, "Please edit VideoViewDemo Activity, and set path" + " variable to your media file URL/path", Toast.LENGTH_LONG).show();
return;
} else {
/*
* Alternatively,for streaming media you can use
* mVideoView.setVideoURI(Uri.parse(URLstring));
*/
mVideoView.setVideoPath(path);
mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
mVideoView.setBufferSize(2048);
mVideoView.requestFocus();
mVideoView.start();
mVideoView.setMediaController(new MediaController(this));
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// optional need Vitamio 4.0
prodlg.dismiss();
mediaPlayer.setPlaybackSpeed(1.0f);
}
});
}
}
I use android platforms 4.0 api 14 play demo :
this is my screen picture demo
If you want to use Vitamio library for displaying video etc, then first of all download Vitamio Library from here Free download Vitamio Library.
then include both "ZI" and "InitActivtiy" (which is inside the Vitamio lib) Library in your current project (right click project-->include library-->), then write this line of code
if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this))
return;
after Oncreate Method() like in my project.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this)) //it will check the include library of Vitamio
return;
after that put this line of code in Androidmanifest.xml file
<!-- (((((( Vitamio Library including in manifest file )))))) -->
<activity android:name="io.vov.vitamio.activity.InitActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|keyboard|keyboardHidden"
android:launchMode="singleTop"
android:theme="#android:style/Theme.NoTitleBar"
android:windowSoftInputMode="stateAlwaysHidden"/>
Now its a time to display your video using VideoView etc.
I have created a following playlist:
#EXTM3U
#EXTINF:3,File - 1
http://pilatus.d1.comp.nus.edu.sg/~a0095695/video_repo/1.mp4
#EXTINF:3,File - 2
http://pilatus.d1.comp.nus.edu.sg/~a0095695/video_repo/2.mp4
#EXTINF:-1,File - 3
http://pilatus.d1.comp.nus.edu.sg/~a0095695/video_repo/3.mp4
#EXT-X-ENDLIST
Also I am using this code to play on my Android device:
MediaController mc = new MediaController(this);
VideoView videoview = (VideoView)findViewById(R.id.myvideoview);
mc.setMediaPlayer(videoview);
videoview.setMediaController(mc);
videoview.setVideoURI(Uri.parse("http://pilatus.d1.comp.nus.edu.sg/~a0095695/video_repo/playlist.m3u8"));
videoview.requestFocus();
videoview.start();
I want Dash streaming, so would create another set of m3u8 files on top of it adapting to the bandwidth
The problem is that I am getting error like "Cannot play the file"
What am I doing wrong?...
Thanks
that is a HLS streaming, and Android 4.0 don't have problems with this format. toyr code are wrong, try to use :
VideoView videoview = (VideoView)findViewById(R.id.myvideoview);
videoview.setMediaController(new MediaController(this));
videoview.setVideoURI(Uri.parse("http://pilatus.d1.comp.nus.edu.sg/~a0095695/video_repo/playlist.m3u8"));
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Android's support for M3U8 playlist is limited. Only newer devices supports the playlist. Some people mentioned they've had luck with devices 2.3.x. As far as I know, this feature was made available in Android 3.0.
See the new features documentation
If you have a supported device to test with and still experience issues, try using the httplive protocol
A mp4 file should play, however.
This is an example of how to play .M3U8 Streaming in Android, but like other programmers says is not fully supported in all the Android devices
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<VideoView
android:id="#+id/myVideoView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main.java
package com.grexample.ooyalalive;
import java.net.URL;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class Main extends Activity {
private String urlStream;
private VideoView myVideoView;
private URL url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_vv);//***************
myVideoView = (VideoView)this.findViewById(R.id.myVideoView);
MediaController mc = new MediaController(this);
myVideoView.setMediaController(mc);
urlStream = "http://jorgesys.net/i/irina_delivery#117489/master.m3u8";
runOnUiThread(new Runnable() {
#Override
public void run() {
myVideoView.setVideoURI(Uri.parse(urlStream));
}
});
}
}
I have seen a lot of people have problems playing .M3U8, it depends on the codecs used for the streaming and compatibility with the device, for example some of my .m3u8 files are only supported in devices with screens of 1200 x800 and higher.
As i understood, Android 3.0 and above are able for play radio streaming m3u8 - http://developer.android.com/guide/appendix/media-formats.html
I put this link - http://content.mobile-tv.sky.com/content/ssna/live/ssnraudio.m3u8 into MediaPlayer but in LogCat i get:
06-01 09:04:44.287: INFO/LiveSession(33): onConnect 'http://content.mobile-tv.sky.com/content/ssna/live/ssnraudio.m3u8'
06-01 09:04:44.287: INFO/NuHTTPDataSource(33): connect to content.mobile-tv.sky.com:80/content/ssna/live/ssnraudio.m3u8 #0
06-01 09:04:44.747: INFO/NuHTTPDataSource(33): connect to content.mobile-tv.sky.com:80/content/ssna/live/ssnraudio.m3u8 #0
06-01 09:04:45.019: INFO/NuHTTPDataSource(33): connect to content.mobile-tv.sky.com:80/content/ssna/live/ssnraudio/ssnr_052311_071632_78731.aac #0
**06-01 09:04:45.817: ERROR/LiveSession(33): This doesn't look like a transport stream...**
06-01 09:04:45.967: INFO/HTTPLiveSource(33): input data EOS reached.
This is my source code:
mp = new MediaPlayer();
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
mp.setDataSource("http://content.mobile-tv.sky.com/content/ssna/live/ssnraudio.m3u8");
mp.prepare();
mp.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.stop();
mp.reset();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Following this link trail:
http://code.google.com/p/android/issues/detail?id=14646
->
http://code.google.com/p/android/issues/detail?id=16884
->
http://code.google.com/p/android/issues/detail?id=17118
(ARGGGGH!)
Gives the answer in the end:
basically in Android v2.3 & v3.0, use the non-standard httplive:// scheme,
in 3.1 use http:// but with some code workaround in how you call the relevant methods in the media framework.
Try ExoMedia, streaming is as easy as:
emVideoView.setVideoURI(Uri.parse("https://archive.org/download/Popeye_forPresident/Popeye_forPresident_512kb.mp4"));
I works well with m3u8.
Maybe you can try the Vitamio plugin, http://vov.io/vitamio/
Vitamio is a multimedia framework for all Android devices. Vitamio works like the Android's default MediaPlayer except that it includes much more powerful features. And it's absolutely free !
Network Protocols
The following network protocols are supported for audio and video playback:
MMS
RTSP (RTP, SDP)
HTTP progressive streaming
HTTP live streaming (M3U8), for Android 2.1+
This is my example of how to play .M3U8 Streaming in Android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<VideoView
android:id="#+id/myVideoView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main.java
package com.grexample.ooyalalive;
import java.net.URL;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class Main extends Activity {
private String urlStream;
private VideoView myVideoView;
private URL url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_vv);//***************
myVideoView = (VideoView)this.findViewById(R.id.myVideoView);
MediaController mc = new MediaController(this);
myVideoView.setMediaController(mc);
urlStream = "http://jorgesys.net/i/irina_delivery#117489/master.m3u8";
runOnUiThread(new Runnable() {
#Override
public void run() {
myVideoView.setVideoURI(Uri.parse(urlStream));
}
});
}
}
I have seen a lot of people have problems playing .M3U8, it depends on the codecs used for the streaming and compatibility with the device, for example some of my .m3u8 files are only supported in devices with screens of 1200 x800 and higher.
You can use FFmpegMediaPlayer:
https://github.com/wseemann/FFmpegMediaPlayer
I also searched a lot to play m3u8 videos in Exo_player , if we use normal exo player to play m3u8 type videos it would not play for this. We need to do some changes , i did and it working fine for me.
In Kotlin :
private var exoPlayer: ExoPlayer? = null
private val playbackStateListener: Player.Listener = playbackStateListener()
private var currentItem = 0
private var playbackPosition = 0L
var url = ""
//Call this method from onStart() of the Activity.
private fun initializePlayer() {
exoPlayer = ExoPlayer.Builder(this).build()
videoView.player = exoPlayer
videoView.setKeepContentOnPlayerReset(true)
var mediaItem = MediaItem.Builder().
setUri("YOUR m3u8 url to play video ")
.setMimeType(MimeTypes.APPLICATION_M3U8).build()
exoPlayer?.let { exoPlayer ->
exoPlayer.setMediaItem(mediaItem)
exoPlayer.playWhenReady = true
exoPlayer.seekTo(currentItem, 20L)
exoPlayer.prepare()
}
}
Now You need to add dependency , do not forget to add dependency in gradle:
implementation 'com.google.android.exoplayer:exoplayer-hls:2.17.1'
Now for your easyness i will show the xml.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="#+id/videoView"
app:show_buffering="always"
app:resize_mode="fit"
app:keep_content_on_player_reset="false"
app:use_controller="true"
android:layout_width="match_parent"
android:layout_height="480dp" >
</com.google.android.exoplayer2.ui.StyledPlayerView>
</LinearLayout>
I am placed video MP4 to my domain space. I have its public URL, Now i want to play it in my android app; but don't know how can I do this. I used following code which is not working. Track controller is moving but I can't see any video on screen.
public class MPlayer extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playvideo);
VideoView videoView = new VideoView(MPlayer.this);
videoView.setMediaController(new MediaController(this));
videoView.setVideoURI(Uri.parse("http://www.semanticdevlab.com/abc.mp4"));
videoView.requestFocus();
videoView.start();
LinearLayout l = (LinearLayout)findViewById(R.id.mplayer);
l.addView(videoView);
}
}
The VideoView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.
Code:
videoView = (VideoView)findViewById(R.id.ViewVideo);
videoView.setVideoURI(Uri.parse(“android.resource://” + getPackageName() +”/”+R.raw.video));
videoView.setMediaController(new MediaController(this));
videoView.requestFocus();
videoView.start();
if you want see source code : Play video file using VideoView in Android
Most of the time, I'm using following code:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
for more information look at this page: http://developer.android.com/guide/topics/media/index.html
and
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Video.html
I think this may help you find some solution.
mp=new MediaPlayer();
mp.setDataSource(path);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(holder);
mp.prepare();
mp.start();
If you are trying this in your emulator, you might have to try it in a real device, because sometimes I too use face the same problem. I will not be able to view the video in emulator, but the video will play without any problem in the mobile. the problem is, I think with the emulator, not with your code.
This is how I played a video file from Network in my project
Required Kotlin, AndroidX
Show a loading dialog while the file is buffering and then start playback:
private fun playVideo(videopath: String) {
Log.e("Playing Video File: ", "" + videopath);
try {
//Show Loader
val builder: AlertDialog.Builder = AlertDialog.Builder(this#ScreenCaptureImageActivity);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
progressDialog = builder.create();
//add Controller
val mediaController = MediaController(this#ScreenCaptureImageActivity);
videoView.setMediaController(mediaController)
//Add URI
//Uncomment to play from local path
//videoView.setVideoURI(Uri.parse(videopath))
//Example Play from Internet
videoView.setVideoPath("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4")
videoView.setOnPreparedListener {
progressDialog!!.dismiss();
//Start Playback
videoView.start()
Log.e(TAG, "Video Started");
}
} catch (e: Exception) {
progressDialog!!.dismiss();
Log.e(TAG, "Video Play Error :" + e.localizedMessage);
}
}
Loader XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ProgressBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="center"
android:text="Please wait! This may take a moment." />
</LinearLayout>
**For Network Access add network config in the manifest, from ANdroid P its required **
<application
...
android:networkSecurityConfig="#xml/network_security_config"
>
Add network_security_config.xml in res/xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
You should do it in onResume, because in onCreate VideoView does not knows its size and can't create properly surface to display video.
public class MPlayer extends Activity{
VideoView videoView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playvideo);
videoView = new VideoView(MPlayer.this);
videoView.setMediaController(new MediaController(this));
LinearLayout l = (LinearLayout)findViewById(R.id.mplayer);
l.addView(videoView);
}
#Override
protected void onResume() {
super.onResume();
videoView.setVideoURI(Uri.parse("http://www.semanticdevlab.com/abc.mp4"));
videoView.start();
}