How to play a video file in android? - android

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();
}

Related

Play video stream using Vitamio library in android?

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.

Android: VideoView not working on some devices

I have a VideoView that works with a lot of devices but not on others. For some time it shows my ProgressDialog and then it fires a Popup that says Impossible to play video (translated from Italian, so it may be different but... you understand).
For example it works on Samsung Galaxy S:
Android version: 2.2.1
Kernel version: 2.6.32.9
But not on HTC Magic
Android version: 2.2
Kernel version: 2.6.34.5
The video I want to show is taken from a URL and it'an MP4 file.
Here's the code:
public class VideoViewActivity extends BaseActivity {
ProgressDialog progDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri videoUri = Uri.parse(getIntent().getStringExtra("url"));
setContentView(R.layout.activity_video_view);
VideoView vv = (VideoView) findViewById(R.id.videoView);
vv.setMediaController(new MediaController(this));
vv.requestFocus();
vv.setVideoURI(videoUri);
vv.start();
if (app.isEnglish()) {
progDialog = ProgressDialog.show(this, getResources().getString(R.string.en_wait), getResources().getString(R.string.en_load), true);
}
else {
progDialog = ProgressDialog.show(this, getResources().getString(R.string.it_wait), getResources().getString(R.string.it_load), true);
}
progDialog.setCancelable(true);
vv.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progDialog.dismiss();
}
});
}
}
That's the layout:
<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"
tools:context=".VideoViewActivity" >
<VideoView
android:id="#+id/videoView"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Any suggestions?
I too had the same iisue while using videoView. I managed it using device's installed media application using intent. They are doing there application for managing media, Why we want to waste our time...
PackageManager packageManager = getPackageManager();
Intent videoIntent = new Intent(Intent.ACTION_VIEW);
videoIntent.setDataAndType(Uri.parse(videoUrlLink),
"video/*");
List listOfSuppApps = packageManager
.queryIntentActivities(videoIntent,
PackageManager.MATCH_DEFAULT_ONLY);
if (listOfSuppApps.size() <= 0) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.No_supported_applications_Installed),
Toast.LENGTH_LONG).show();
} else {
Intent intnt = new Intent(Intent.ACTION_VIEW);
intnt.setDataAndType(Uri.parse(urlLink), mediaType+"/*");
context.startActivity(intnt);
}
The above is my code

Streaming m3u8 playlist on Android 4.0.3

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.

How to play m3u8 on Android?

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>

how to play .3GP video file in android

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.

Categories

Resources