Android: Play local video with mediaplayer - android

I am trying to play a video i have saved in my project. I have download this
(an .mp4 test video) then created a folder within my project called vid on the root of the project. I have then used this code:
public void PlayLocalVideo(View view)
{
VideoView video=(VideoView) findViewById(R.id.video1);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(video);
video.setMediaController(mediaController);
video.setKeepScreenOn(true);
video.setVideoPath("android.resource://uk.co.SplashActivity/vid/big_buck_bunny.mp4");
video.start();
video.requestFocus();
}
my xml looks like this:
<VideoView
android:id="#+id/video1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
PlayLocalVideo is a method i have then used on the onclick event on a button. but when i press play nothing happens :(

Just paste the file into res/raw/big_buck_bunny.mp4 instead vid folder and change
your videoPath to:
video.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.big_buck_bunny);

The problem may be in Android OS defect, which doesn't let you access normally files more than 1Mb size Load files bigger than 1M from assets folder
You probably need to split your video file into 1Mb sized parts. Then merge this parts into one file on sdcard and play it.
For example, I've splited big_buck_bunny.mp4 into 5 parts big_buck_bunny.mp4.part0, big_buck_bunny.mp4.part1 and so on. To merge them you can use this method
private void copyVideoFromAssets(String inFilePrefix, String outFileName) throws IOException {
// Get list of files in assets and sort them
final String[] assetsFiles = getAssets().list("");
Arrays.sort(assetsFiles);
// Open the empty file as the output stream
final OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024 * 128];
for (String file: assetsFiles) {
if (file.startsWith(inFilePrefix)) {
// Open part of file stored in assets as the input stream
final InputStream input = getAssets().open(file);
// Transfer bytes from the input file to the output file
int length = input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
input.close();
}
}
// Close the streams
output.flush();
output.close();
}
public void PlayLocalVideo(View view)
try {
copyVideoFromAssets("big_buck_bunny.mp4.part", "/mnt/sdcard/big_buck_bunny.mp4");
} catch (IOException e) {
e.printStackTrace();
}
VideoView video=(VideoView) findViewById(R.id.video);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(video);
video.setMediaController(mediaController);
video.setKeepScreenOn(true);
video.setVideoPath("/mnt/sdcard/big_buck_bunny.mp4");
video.start();
video.requestFocus();
}

Try this code....
1st make folder name raw in res directory, Copy your video in that folder and try out this code...
video1=(VideoView)findViewById(R.id.myvideoview);
video1.setVideoURI(Uri.parse("android.resource://" +getPackageName()+ "/"+R.raw.YOUR_VIDEO_FILE_NAME));
video1.setMediaController(new MediaController(this));
video1.requestFocus();
video1.start();

Related

Android APK Expansion File, Cannot read .wav files

I have been developing an App which need to play sounds and have large set of sounds files in .wav format that boast arounds near 1GB size. I have followed the official documentation for making the Expansion file.
First i made a .zip file with 0 compressions, all .wav files are under that files (without any subfolder. that is main.1.package contains all the sounds file).Then i renamed the .zip folder into .obb. After that i put that .obb file inside the apps folder under shared storage obb folder (com.moinul.app is my package name, so the folder name was it, also the expansion file were named main.1.com.moinul.app.obb )
Problem is when i try to read the files from my expansion files i get null pointer exceptions:
try
{
String param = (String) v.getTag();
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(context, 1, 0);
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("p25_1.wav");
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(fd.getFileDescriptor());
mPlayer.prepare();
mPlayer.start();
}
catch (Exception e)
{
Log.w(TAG, e.getMessage() + "");
e.printStackTrace();
}
I get exceptions saying that fd is null. Any help would be appreciated.
Thanks
Try use: AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("assets/p25_1.wav");
Try
`public class Test extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String TAG = "Test";
Context context = this;
try {
MediaPlayer mediaPlayer = new MediaPlayer();
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(context, 1, 0);
AssetFileDescriptor assetFileDescriptor = expansionFile.getAssetFileDescriptor("assets/p25_1.wav");
if (assetFileDescriptor != null) {
final FileInputStream fis = assetFileDescriptor.createInputStream();
if (fis != null) {
mediaPlayer.setDataSource(fis.getFD());
fis.close();
mediaPlayer.prepare();
mediaPlayer.start();
} else {
Log.w(TAG, "/fis: null");
}
}
} catch (Exception e) {
Log.w(TAG, e.getMessage() + "");
}
}
}`
Ok so it worked finally. After changing into :
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("Sounds/p25_1.wav");
Its working now. Its weird that i had to add Sounds, which was the folder name before compress (i actually compressed this folder and all .wav are under it). I think the compressor made another subfolder inside the .zip.
Anyway thanks for the help.

Android - Playing MP4 video file from an expansion file

I have followed all the steps in testing an expansion file for my application. Where I am stuck now is how to play a video file contained in that expansion file.
I have successfully been able to download it from Google Play, and I can see it in the folder it is supposed to be in when I browse through my file manager.
I have looked for the past couple of days in trying to figure out how to play the file. At the moment there is only one for, to maintain appropriate size for testing.
I have tried to parse the URI and set it in the videoview, however, it always shows that the video cannot be played.
I have also tried this code so far to access it (as read in the documentation, and I have replaced the parameters with my parameters):
// Get a ZipResourceFile representing a merger of both the main and patch files
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext,
mainVersion, patchVersion);
// Get an input stream for a known file inside the expansion file ZIPs
InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
What do I do with the input stream in order to play the video?
Code for provider
public class EHZipUriProvider extends APEZProvider {
#Override
public String getAuthority() {
// TODO Auto-generated method stub
return "your.package.name.Utility.EHZipUriProvider";
}
}
Custom video player
public static final Uri CONTENT_URI = Uri
.parse("content://your.package.name.Utility.EHZipUriProvider");
public static VideoView mview;
public static void playVideo(Context context, VideoView resource, String VIDEO_NAME) {
position = 0;
mview = resource;
Uri video = Uri.parse((CONTENT_URI + "/" + VIDEO_NAME));
mview.setVideoURI(video);
mview.start();
mview.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mview = null;
}
});
}
Calling in activity
VideoPlayer.playVideo(context, vv, "rulesofenglish.mp4");
For example, my application package name is:
com.bluewindsolution.android.sampleapp
Then my expansion file should be
main.1.com.bluewindsolution.android.sampleapp.obb
In detail, you can follow in here:
[main|patch].< expansion-version >.< package-name >.obb
From expansion you can get it via three ways:
via AssetFileDescriptor
// This one works with an image file and a media file.
// Get a ZipResourceFile representing a specific expansion file
// mainContext, version number of your main expansion, version number of your patch
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(this, 1, 0);
AssetFileDescriptor afd_img1 = expansionFile.getAssetFileDescriptor("your_path/your_file.jpg");
AssetFileDescriptor afd_mpbg = expansionFile.getAssetFileDescriptor("your_path/your_file.mp3");
// To set image
ImageView imageView1 = (ImageView)findViewById(R.id.iv1);
imageView1.setImageBitmap(BitmapFactory.decodeFileDescriptor(afd_iv1.getFileDescriptor()));
// To set sound
try {
mpbg.setDataSource(afd_mpbg.getFileDescriptor(), afd_mpbg.getStartOffset(), afd_mpbg.getDeclaredLength());
mpbg.prepareAsync();
mpbg.start();
} catch (IllegalStateException e) {
Log.w("Error=====", "Failed to prepare media player", e);
}
Via InputStream:
// This one works with an image file and a media file.
// Get a ZipResourceFile representing a specific expansion file
ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip);
// Get an input stream for a known file inside the expansion file ZIPs
InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
Via Uri
// This one can use in almost thing such as jpg, mp3, mp4, pdf, etc.
// You need to create a new class to override APEZProvider
public class ZipFileContentProvider extends APEZProvider {
#Override
public String getAuthority() {
return "com.bluewindsolution.android.sampleapp";
}
}
// You need to add <provider> in AndroidManifest.xml
<provider
android:name="com.bluewindsolution.android.sampleapp.ZipFileContentProvider"
android:authorities="com.bluewindsolution.android.sampleapp"
android:exported="false"
android:multiprocess="true"
>
<meta-data android:name="mainVersion"
android:value="1"></meta-data>
</provider>
// After that, you can use it any time by this code:
String filename2 = "image/i_commu_a_1_1_1_1.jpg"; // suppose you store put your file in directory in .obb
String uriString2 = "content://com.bluewindsolution.android.sampleapp" + File.separator + filename2;
Uri uri2 = Uri.parse(uriString2);
imageView2.setImageURI(uri2);
// Filename inside my expansion file
String filename = "video/v_do_1_1_1.mp4"; // Suppose you store put your file in directory in .obb
String uriString = "content://com.bw.sample_extension_download_main" + File.separator + filename;
Uri uri = Uri.parse(uriString);
v1 = (VideoView)findViewById(R.id.videoView1);
v1.setVideoURI(uri);
v1.start();
Using a provider (the best solution for me)! I tested it, and it works perfectly.
See Android: read media file from .obb using APEZ.

Reading mp3 from expansion file

Reading mp3 file from expansion file
I have create and expansion file with name
"main.1.com.example.app.obb"
which contains and audio file name "about_eng.mp3"
Now the issue i have written the following code to read and play the mp3 file
private final static String EXP_PATH = "/Android/obb/";
static String[] getAPKExpansionFiles(Context ctx, int mainVersion, int patchVersion) {
String packageName = ctx.getPackageName();
Vector<String> ret = new Vector<String>();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Build the full path to the app's expansion files
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + EXP_PATH + packageName);
// Check that expansion file path exists
if (expPath.exists()) {
if ( mainVersion > 0 ) {
String strMainPath = expPath + File.separator + "main." +
mainVersion + "." + packageName + ".obb";
File main = new File(strMainPath);
if ( main.isFile() ) {
ret.add(strMainPath);
}
}
if ( patchVersion > 0 ) {
String strPatchPath = expPath + File.separator + "patch." +
mainVersion + "." + packageName + ".obb";
File main = new File(strPatchPath);
if ( main.isFile() ) {
ret.add(strPatchPath);
}
}
}
}
String[] retArray = new String[ret.size()];
ret.toArray(retArray);
return retArray;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Get a ZipResourceFile representing a merger of both the main and patch files
try {
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(this,1,1);
if(expansionFile!=null){
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("about_eng.mp3");
//or
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource( fd.getFileDescriptor(),
fd.getStartOffset(),fd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get an input stream for a known file inside the expansion file ZIPs
}
But it is always throwing exception at this line
mediaPlayer.setDataSource( fd.getFileDescriptor(),
fd.getStartOffset(),fd.getLength());
mediaPlayer.prepare();
because the variable fd is null.
Can any body help me to solve this
i have googled and found that we shold have to make .zip with 0% (No compression) that is mention in http://developer.android.com/google/play/expansion-files.html
Tip: If you're packaging media files into a ZIP, you can use media playback calls on the files with offset and length controls (such as MediaPlayer.setDataSource() and SoundPool.load()) without the need to unpack your ZIP. In order for this to work, you must not perform additional compression on the media files when creating the ZIP packages. For example, when using the zip tool, you should use the -n option to specify the file suffixes that should not be compressed:
zip -n .mp4;.ogg main_expansion media_files
so How to make 0% compression zip using winrar?
here see the compression method
so we should have to upload this zip in play store.
so you not need to use ZipHelper.java that is mentioned in other SO answer
just simply use
ZipResourceFile expansionFile=null;
try {
expansionFile = APKExpansionSupport.getAPKExpansionZipFile(getApplicationContext(),3,0);
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("test.mp3");
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(fd.getFileDescriptor(),fd.getStartOffset(),fd.getLength());
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try to use expansionFile.getAssetFileDescriptor("main_expansion/about_eng.mp3").
If it doesn't work, call this:
ZipResourceFile.ZipEntryRO [] entries = expansionFile.getAllEntries();
and look at the file names:
entries[0].mFileName;.
That could be a hint how the path should look like.
I know that the question is old, but maybe it helps someone.
To read mp3, with mediaplayer, you can do it 3 ways
for example. my application package name is
com.bluewindsolution.android.sampleapp
then my expansion file should be
main.1.com.bluewindsolution.android.sampleapp.obb
in detail, you can followed in here
[main|patch].< expansion-version >.< package-name >.obb
From expansion you can get it via 3 ways:
via AssetFileDescriptor
// this one work with image file, media file
// Get a ZipResourceFile representing a specific expansion file
// mainContext, version no. of your main expansion, version no of your patch
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(this, 1, 0);
AssetFileDescriptor afd_img1 = expansionFile.getAssetFileDescriptor("your_path/your_file.jpg");
AssetFileDescriptor afd_mpbg = expansionFile.getAssetFileDescriptor("your_path/your_file.mp3");
// to set image
ImageView imageView1 = (ImageView)findViewById(R.id.iv1);
imageView1.setImageBitmap(BitmapFactory.decodeFileDescriptor(afd_iv1.getFileDescriptor()));
// to set sound
try {
mpbg.setDataSource(afd_mpbg.getFileDescriptor(), afd_mpbg.getStartOffset(), afd_mpbg.getDeclaredLength());
mpbg.prepareAsync();
mpbg.start();
} catch (IllegalStateException e) {
Log.w("Error=====", "Failed to prepare media player", e);
}
via InputStream
// this one work with image file, media file
// Get a ZipResourceFile representing a specific expansion file
ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip);
// Get an input stream for a known file inside the expansion file ZIPs
InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
via Uri
//this one can use in almost thing such as jpg, mp3, mp4, pdf, etc.
//you need to create new class to override APEZProvider
public class ZipFileContentProvider extends APEZProvider {
#Override
public String getAuthority() {
return "com.bluewindsolution.android.sampleapp";
}
}
//you need to add <provider> in AndroidManifest.xml
<provider
android:name="com.bluewindsolution.android.sampleapp.ZipFileContentProvider"
android:authorities="com.bluewindsolution.android.sampleapp"
android:exported="false"
android:multiprocess="true"
>
<meta-data android:name="mainVersion"
android:value="1"></meta-data>
</provider>
//after that you can use it any time by this code:
String filename2 = "image/i_commu_a_1_1_1_1.jpg"; // suppose you store put your file in directory in .obb
String uriString2 = "content://com.bluewindsolution.android.sampleapp" + File.separator + filename2;
Uri uri2 = Uri.parse(uriString2);
imageView2.setImageURI(uri2);
// Filename inside my expansion file
String filename = "video/v_do_1_1_1.mp4"; // suppose you store put your file in directory in .obb
String uriString = "content://com.bw.sample_extension_download_main" + File.separator + filename;
Uri uri = Uri.parse(uriString);
v1 = (VideoView)findViewById(R.id.videoView1);
v1.setVideoURI(uri);
v1.start();

Android: how to play video from assets?

I am making an application in which I have to show video from assets folder in a Fragment. Can anyone help me do this? Do I need to use VideoView in XML?
Instead of accessing from assests,You must copy the video into your project's res/raw folder.
Create raw folder under res folder.
It must be in a supported format (3gp, wmv, mp4 ) and named with lower case, numerics, underscores and dots in its filename likewise:video_file.mp4.
VideoView view = (VideoView)findViewById(R.id.videoView);
String path = "android.resource://" + getPackageName() + "/" + R.raw.video_file;
view.setVideoURI(Uri.parse(path));
view.start();
VideoView view = (VideoView)findViewById(R.id.videoView);
String path = "android.resource://" + getPackageName() + "/" + R.raw.video_file;
view.setVideoURI(Uri.parse(path));
view.start();
It's AkashG's code, but I remember that R here is not from the Android class.
It's from your own project.
You first need to convert your video into the InputStream and then save it to the user's internal storage, then display it and delete that file when the video is finished.
try{
String path = Environment.getExternalStorageDirectory()+"/"+APP_NAME()+"/videos/"+ls+"/" ;
InputStream input = getAssets().open("vid/dal.mp4");
String name = System.currentTimeMillis() +".mp4";
File f = new File(path);
f.mkdirs();
int size = input.available();
FileOutputStream output = new FileOutputStream(new File(path+name));
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
if (size <= total) {
break;
}
}
output.flush();
output.close();
input.close();
//Toast.makeText(VideoPlayer.this , "file created !" , Toast.LENGTH_LONG).show();
Uri uri = Uri.parse(path+name) ;
videoView.setVideoURI(uri);
videoview.start();
}cath(Exception e){
}
I have already suffered from same problem, u should prefer project's res/raw folder instead of assets. Create raw folder under res folder. Save video file in a supported format (3gp, wmv, mp4 ) and named with lowercase, numerics, underscores and dots in its filename likewise:filename.3gp into the raw folder.
VideoView videoview = (VideoView) findViewById(R.id.VideoView);
String uriPath = "android.resource://your application package name/raw/your
wmv/mp4/3gp file in res/raw path without extension";
videoview.setVideoURI(Uri.parse(uriPath));
videoview.start();
you can use the MediaItem to play a video from assets
val playerView = view.findViewById<StyledPlayerView>(R.id.player)
val player = ExoPlayer.Builder(context!!).build()
val videoUri = Uri.parse("asset:///test.mp4")
val item = MediaItem.fromUri(videoUri)
player.addMediaItem(item)
playerView.player = player
player.prepare()
Playing Video(sample.mp4) present in res/ raw folder, along with the Media Controller
// Import Statements
import android.widget.VideoView;
import android.widget.MediaController;
public class youractiviy extends Activity {
private VideoView videoView;
private MediaController mediaController;
protected void onCreate(Bundle savedInstanceState) {
// Your Startup code
videoView = (VideoView) findViewById(R.id.video_view);
videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.sample);
mediaController = new MediaController(TestActivity.this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.start();
}
}
// XML Code
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Can a videoview play a video stored on internal storage?

I'm trying to provide my users with the ability to use either external or internal storage. I'm displaying both images and videos (of a scientific nature). When storing the media on the SD card, all is fine. But when I store the media internally, only the images will display. No matter what I try I get various errors when trying to load and display the media stored under the applicationcontext.getFilesDir().
Is there a trick to setting a videoview's content to such a file?
Can a ContentResolver help me?
On a related note, is it considered bad form to assume that external storage exists?
Thanks in advance,
Sid
Below is one version that fails with "Cannot play video. Sorry, this video cannot be played". But I have many other modes of failure. I can copy the internal video to temp storage (external) and play it, so this copy to internal does indeed create a valid movie. It only fails when I try to play it directly from the internal storage.
videoFile = new File(this.getFilesDir() + File.separator + "test.mp4");
InputStream data = res.openRawResource(R.raw.moviegood);
try {
OutputStream myOutputStream = new FileOutputStream(videoFile);
byte[] buffer = new byte[8192];
int length;
while ( (length = data.read(buffer)) > 0 ) {
myOutputStream.write(buffer);
}
//Close the streams
myOutputStream.flush();
myOutputStream.close();
data.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vview.setKeepScreenOn(true);
vview.setVideoPath(videoFile.getAbsolutePath());
vview.start();
MediaPlayer requires that the file being played has world-readable permissions. You can view the permissions of the file with the following command in adb shell:
ls -al /data/data/com.mypackage/myfile
You will probably see "-rw------", which means that only the owner (your app, not MediaPlayer) has read/write permissions.
Note: Your phone must be rooted in order to use the ls command without specifying the file (in the internal memory).
If your phone is rooted, you can add world-read permissions in adb shell with the following command:
chmod o+r /data/data/com.mypackage/myfile
If you need to modify these permissions programmatically (requires rooted phone!), you can use the following command in your app code:
Runtime.getRuntime().exec("chmod o+r /data/data/com.mypackage/myfile");
Which is basically a linux command. See https://help.ubuntu.com/community/FilePermissions for more on chmod.
EDIT: Found another simple approach here (useful for those without rooted phones). Since the application owns the file, it can create a file descriptor and pass that to mediaPlayer.setDataSource():
FileInputStream fileInputStream = new FileInputStream("/data/data/com.mypackage/myfile");
mediaPlayer.setDataSource(fileInputStream.getFD());
This approach avoids the permission issue completely.
You can use:
videoView.setVideoURI(Uri.parse(file.getAbsolutePath()));
if the file is world readable
Or you can use a content provider
For detail check this tutorial
public class AndroidVideoViewExample extends Activity {
private VideoView myVideoView;
private int position = 0;
private ProgressDialog progressDialog;
private MediaController mediaControls;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the main layout of the activity
setContentView(R.layout.activity_main);
//set the media controller buttons
if (mediaControls == null) {
mediaControls = new MediaController(AndroidVideoViewExample.this);
}
//initialize the VideoView
myVideoView = (VideoView) findViewById(R.id.video_view);
// create a progress bar while the video file is loading
progressDialog = new ProgressDialog(AndroidVideoViewExample.this);
// set a title for the progress bar
progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
// set a message for the progress bar
progressDialog.setMessage("Loading...");
//set the progress bar not cancelable on users' touch
progressDialog.setCancelable(false);
// show the progress bar
progressDialog.show();
try {
//set the media controller in the VideoView
myVideoView.setMediaController(mediaControls);
//set the uri of the video to be played
myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.kitkat));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
//we also set an setOnPreparedListener in order to know when the video file is ready for playback
myVideoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
// close the progress bar and play the video
progressDialog.dismiss();
//if we have a position on savedInstanceState, the video playback should start from here
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
//if we come from a resumed activity, video playback will be paused
myVideoView.pause();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
myVideoView.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position
position = savedInstanceState.getInt("Position");
myVideoView.seekTo(position);
}
}
I posted a custom VideoView implementation there.
The VideoView implementation has the setVideoFD(FileDescriptor fd) method and solves this issue.
I came across this thread with the same problem, I'm downloading my videos from the web to the internal storage, turns out when saving you can specify the RW mode, i.e change from PRIVATE to WORLD_READABLE
URL url = new URL(_url);
InputStream input = null;
FileOutputStream output = null;
try {
String outputName = "video.mp4";
input = url.openConnection().getInputStream();
output = c.openFileOutput(outputName, Context.MODE_WORLD_READABLE);
int read;
byte[] data = new byte[5120]; //5MB byte array
while ((read = input.read(data)) != -1)
output.write(data, 0, read);
return true;
} finally {
if (output != null)
output.close();
if (input != null)
input.close();
}
}
You can't just play it directly.
You need to implement a ContentProvider then pass the defined Uri to setVideoUri(uri) method.

Categories

Resources