Play video file from internal storage android using VideoView

baradas picture baradas · May 15, 2012 · Viewed 36.2k times · Source

Am trying to play a video stored in the internal storage in Android. However, no matter what I do it keeps coming back with either a -1 error or a -38 error. Both seem to be rather generic errors hence are not much intelligible.

I am wondering if it is possible to use a VideoView and not a MediaPlayer instance to play a video file from the local storage.

The steps involved in my app include,

  1. downloading a file from a remote url
  2. Storing the file in internal storage (note i use the convention for ensuring that it has global read permissions. i.e

    openFileOutput(file_name, Context.MODE_WORLD_READABLE);
    
  3. Reading the media file back at a later point from this location, and playing it in a videoView.

    String filePath = "file://" + getFilesDir()+File.separator+file_name;
    Uri videoUri = Uri.parse(filePath);
    Log.d("Video Player", filePath);
    videoPlayer.setVideoURI(videoUri);
    

I also went through other links in StackOverflow which point out that I need to implement a CustomContentProvider to be able to read these files. Is there a direct way of accessing the file uri and setting it to the videoView without having to resorting to creating a custom content provider and using a mediaPlayer instead of a videoView.

Other StackOverflow references used

  1. Android - Load video from private folder of app
  2. Can a videoview play a video stored on internal storage?

Answer

Joshua Pinter picture Joshua Pinter · Mar 18, 2014

Copy it to External Storage (Temporarily)

I ran into the same issue as you and resorted to just simply copying the file temporarily to external storage before playing it and then deleting the temporary file afterwards.

Here is some sample code that I used to do this:

try {
  // Copy file to temporary file in order to view it.
  temporaryFile = generateTemporaryFile(file.getName());
  FileUtils.copyFile(file, temporaryFile);
  previewVideo(temporaryFile, videoView);

} catch (IOException e) {
  e.printStackTrace();
}


# Helpers

protected File generateTemporaryFile(String filename) throws IOException {
  String tempFileName = "20130318_010530_";

  File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

  File tempFile = File.createTempFile(
      tempFileName,       /* prefix     "20130318_010530" */
      filename,           /* filename   "video.3gp" */
      storageDir          /* directory  "/data/sdcard/..." */
  );

  return tempFile;
}

protected void previewVideo(File file, VideoView videoView) {
  videoView.setVideoPath(file.getAbsolutePath());

  MediaController mediaController = new MediaController(this);

  videoView.setMediaController(mediaController);

  mediaController.setMediaPlayer(videoView);

  videoView.setVisibility(View.VISIBLE);

  videoView.start();
}