Android: how to play video from assets? - android

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" />

Related

checking a file if it exist or not exist (not working)

I am trying to check the mp3 file located to my raw folder under my res. my mp3 file is exist but my code gives me a false return.
String filename = "android.resource://" + this.getPackageName() + "/raw/w";
Toast.makeText(ViewPager.this, mp3check(filename)+"",Toast.LENGTH_LONG).show();
checking the mp3 file
public boolean mp3check(String _filename) {
return new File(_filename).exists();
}
I don't think you can treat a raw resource as a regular file.
Since it is a resource, there is no need to check if it exists.
You can open it using the resource ID.
For example, if your file is named, mysong.mp3, you can open it like this:
InputStream is = getResources().openRawResource(R.raw.mysong);
or
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.mysong);
You can use the AssetFileDescriptor to play it with a MediaPlayer.
try this
String filename = "android.resource://" + this.getPackageName() + "/raw/w";
String newFilePath = "new file path"; // ExternalStorageDirectory path
final Path destination = Paths.get(newFilePath );
try (
final InputStream in = getResources().openRawResource(R.raw.w);
) {
Files.copy(in, destination);
}
Toast.makeText(ViewPager.this, mp3check(filename)+"",Toast.LENGTH_LONG).show();
public boolean mp3check(String _newFilePath) {
return new File(_newFilePath).exists();
}

Where to put the Video file in android Project

I have a video, I need to know where to place and how to get the path of that video.
I know how to add the video form URL,
Uri uri=Uri.parse("www.abc.com/myVid.mp4");
videoView = (VideoView) findViewById(R.id.videoView);
videoView.setVideoURI(uri);
This works fine, but now the video file is in my project, I need to know how to get the path from the folder structure
Kindly guide me.
Thanks
You can create asset folder inside your project and store your video in that folder.
Then you can get that using getAssets() function which is provided by Android.
EDIT 1:
You can click on the Project window, press Alt-Insert, and select Folder -> Assets Folder. Android Studio will add it automatically to the correct location.
Also, you can do this.
VideoView view = (VideoView)findViewById(R.id.videoView);
String path = "android.resource://" + getPackageName() + "/" + R.raw.video_file;
view.setVideoURI(Uri.parse(path));
view.start();
Where video_file is your file name.
You can Create a folder under Resources and Name it raw. Then to provide the Path to the Video you can simply do
String path = "android.resource://" + getPackageName() + "/"
+ R.raw.intro_land;
and then
videoplayer.setVideoURI(Uri.parse(path));
You can view your own video by creating a folder under res as follows:
Right click on res -> New -> Android Resource Directory
select Resource type as raw
Then you can upload your video into this directory.
VideoView videoView = videoViewFragment.findViewById(R.id.videoView);
String path = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.video01;
herevideoView.setVideoURI(Uri.parse(path));
videoView.start();
video01 is your mp4 file name
You can create raw folder under res and put your video there,
Check this
VideoView mVideoView = (VideoView)findViewById(R.id.videoview);
String uriPath = "android.resource://com.android.AndroidVideoPlayer/"+R.raw.k;
Uri uri = Uri.parse(uriPath);
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();

How can I get video from file Explorer

I developed android application about video saving and play it from phone storage. I saved it but I don't get it and I don't save it. I shared photo location in below how can I get it and play it? I tried like below but I don't do it.
SDCardRoot = new File(getFilesDir() + "/videos");![picture shows video location][2]
File[] videos = SDCardRoot.listFiles();
try {
FileInputStream fi = new FileInputStream(videos[1]);
Log.i("fii", "" + fi);
MediaPlayer pl = new MediaPlayer();
pl.setDataSource(fi.getFD());
pl.prepare();
pl.start();
VideoView vv;
vv = (VideoView) findViewById(R.id.videoView1);
vv.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(sUriPath);
vv.setVideoURI(uri);
vv.setMediaController(new MediaController(MainActivity.this));
vv.requestFocus();
vv.start();

How to play video from raw folder with Android device?

Please help,
How to play videos in android device from raw folder for offline mode?
Successful example1: I can play the video from SDcard used the below code.
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/mp4";
Uri uri = Uri.parse("file:///sdcard/test.mp4");
intent.setDataAndType(uri, type);
startActivity(intent);
Failed example2:
Question: May I put the test.mp4 to res/raw folder?
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/mp4";
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.taipei);
intent.setDataAndType(uri, type);
startActivity(intent);
Have anyone can help me? Please.
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();
Create videoView in your xml file.
// To get files from any resource folder (eg: raw, drawable, etc.)
// Use the resource id
int rawId = getResources().getIdentifier(file_name_without_extension, "raw", getPackageName());
// URI formation
String path = "android.resource://" + getPackageName() + "/" + rawId;
// Set the URI to play video file
videoView.setVideoURI(Uri.parse(path));
Check this solution How to play videos in android from assets folder or raw folder?
VideoView videoHolder = new VideoView(this);
//if you want the controls to appear
videoHolder.setMediaController(new MediaController(this));
Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.your_raw_file); //do not add any extension
//if your file is named sherif.mp4 and placed in /raw
//use R.raw.sherif
in my code "applicationdemo" is the the name of my video file.
String video_url = "android.resource://" + context.getPackageName() + "/" + R.raw.applicationdemo;
final VideoView videoView = findViewById(R.id.dialog_video);
Uri videoUri = Uri.parse(video_url);
MediaController mediaController= new MediaController(context);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(videoUri);
videoView.requestFocus();
videoView.start();
I struggled with this for dynamic video names. The solution that worked for me was:
//Somewhere set the video name variable
String video+name="myvideo";
//setup up and play video
VideoView videoView=(VideoView)findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
String uriPath = "android.resource://"+getPackageName()+"/raw/"+ video_name;
Uri UrlPath=Uri.parse(uriPath);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(UrlPath);
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
if (position == 0) {
try{
videoView.requestFocus();
videoView.start();
}catch (Exception e){
System.out.printf("Error playing video %s\n", e);
}
}else{
videoView.pause();
}
}
});
And in XML
<VideoView android:layout_width="300dp"
android:id="#+id/video"
android:layout_height="300dp"
android:orientation="horizontal"
android:layout_gravity="center"
android:keepScreenOn="true"
/>
i think , everyone gave an answer, but doesn't explain the scenario. The main problem here is, If im not mistaken , Android assume that the video coming from your SD Card is dynamic, where in it could be possible , that the format is not supported or supported, thus it enables / ask you to select or open for other third party media software.
While anything you play UNDER RAW folder, requires a handler such as videoview or built in media player which leads to conclusion that anything you put in your RAW folder should be supported / readable by the Android OS.
However , the thread starter here wants that his RAW files , to be played using a third party media player.
This Solution will exactly helps you that what you want.
VideoView myVideo;
private MediaController media_control;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myVideo = (VideoView) findViewById(R.id.playVideo);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bootanimation_nexus);
media_control = new MediaController(this);
myVideo.setMediaController(media_control);
myVideo.setVideoURI(uri);
myVideo.start();
}
player = ExoPlayerFactory.newSimpleInstance(requireActivity(), new DefaultTrackSelector(), new DefaultLoadControl());
Uri uri = RawResourceDataSource.buildRawResourceUri(getOfflineVideo(offlinePosition));
MediaSource mediaSource = new ExtractorMediaSource(uri, new DefaultDataSourceFactory(requireActivity(),
"MyExoplayer"), new DefaultExtractorsFactory(), null, null);
//setup player with mediaSource

Android: Play local video with mediaplayer

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

Categories

Resources