How to get Duration of captured video in android? - android

Using below code i captured Video,but how to get duration of captured video in android ?
and also when sometimes user discard video and record new video then get duration of new video .
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(cameraIntent, TAKE_VIDEO);

I think the easiest way is:
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(uriOfFile);
int duration = mp.getDuration();
mp.release();
/*convert millis to appropriate time*/
return String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
);

Using cursor you can get duration and there are duration Column in Cursor and you can get as a string.
Cursor cursor = MediaStore.Video.query(getContentResolver(),data.getData(),
new String[] { MediaStore.Video.VideoColumns.DURATION });
System.out.println(">>>>>>>>>>"+cursor.getCount());
cursor.moveToFirst();
String duration = cursor.getString(cursor.getColumnIndex("duration"));

MediaPlayer is a heavy object. Use MediaMetadataRetriever instead
fun getMediaDurationMs(context: Context, fileUri: Uri): Int? {
val mmr = MediaMetadataRetriever()
mmr.setDataSource(context, fileUri)
return mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toInt()
}

Related

Android: How do I get thumbnail from a Video (Uri)

I want thumbnail from a video at any specific position. I am using ThumbnailUtils in order to get thumbnail from video uri and assigning to bitmap but I am getting null value on bitmap.
Any reasons how this is happening and how do I fix this?
selectedVideoUri = data.getData();
bitmap = ThumbnailUtils.createVideoThumbnail(getRealPathFromURI(videoUri),
MediaStore.Images.Thumbnails.MINI_KIND);
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
You can use Glide to load thumb directly to imageview
Glide.with(activity).load(videoPath).into(imageview);
First Load Video List with its path in Your array list using below method
private void loadData(String currentAppPath) {
hiddenpath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + currentAppPath);
String[] fileName = hiddenpath.list();
try{
for(String f : fileName){
if(HelpperMethods.isVideo(f)){
videoFiles.add(hiddenpath.getAbsolutePath()+"/"+f);
}
}
new Loader().loadImages(Environment.getExternalStorageState());
}catch (Exception e){
}
}
You need Loader().loadImages method so i declare this method in separate class file. see below code
public class Loader {
String[] imagieFiles;
public void loadImages(String path){
Log.e("path",path);
System.out.println(path);
} }
Then after You can use below Code to Get Video Thumbnail. By default Each Video Store two size Thumbnail.
1) MINI -- MediaStore.Images.Thumbnails.MINI_KIND and
2) MICRO -- MediaStore.Images.Thumbnails.MICRO_KIND
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(filePath,
MediaStore.Images.Thumbnails.MINI_KIND);
BitmapDrawable bitmapDrawable = new BitmapDrawable(thumb);
contentViewHolder.videoView.setImageBitmap(thumb);
This is supported by Android natively using MediaPlayer SeekTo method
If you just want to show the video placeholder to display then you can use below code:
video_view.setVideoPath(videoPath);
video_view.seekTo(3000); // in milliseconds i.e. 3 seconds
ThumbnailUtils returns null when file or video is corrupted.
but I wanted to only use Uri and this is a good solution to do this:
val mmr = MediaMetadataRetriever()
mmr.setDataSource(videoUri)
val thummbnailBitmap = mmr.frameAtTime
imageView.setImageBitmap(thummbnailBitmap)

Getting thumbnail URI from a new video added to MediaStore

I'm recording video with my app and on stop the video is added to Android MediaStore in order to appear in the video gallery.
I need to get the thumbnail URI as soon the video is added to the gallery.
How I can do this ?
Below, the code I'm using to add the video to gallery:
private void addVideoGallery() {
long dateTaken=System.currentTimeMillis();
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(outputfilename));
int duration = mp.getDuration();
mp.release();
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, outputfilename);
values.put(MediaStore.Video.Media.DATE_TAKEN, dateTaken);
values.put(MediaStore.Video.Media.DURATION, duration);
ContentResolver resolver = MainActivity.this.getContentResolver();
resolver.insert(Video.Media.EXTERNAL_CONTENT_URI, values);
}

How do i play a song in a media player after i got its path

After I get location of the song in the sd card. So how do I use the path, to make a basic music player i.e play button, pause button etc.
Use MediaPlayer for it.
Heres a code sample for playing song, here's a tutorial which explains how to do the rest of your need.
To start song:
MediaPlayer mediaPlayer = new MediaPlayer()
MediaController mc = new MediaController(mediaPlayer);
mc.setDataSource(Path);
mc.prepare();
mc.start();
To Pause:
mediaPlayer.pause()
To Forward:
int temp = (int)startTime;
if((temp+forwardTime)<=finalTime){
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
To Rewind:
int temp = (int)startTime;
if((temp-backwardTime)>0){
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);

How to know the length of an audio recording in Android

I am using the following code to record audio:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "Select audio source"), CardList.ACTIVITY_RECDAUDIO);
When the result comes back I do the following:
Uri u = intent.getData();
String audioUri = u.getPath();
InputStream in = new BufferedInputStream(this.getContentResolver().openInputStream(u));
I would like to know how long the recording is in seconds. Is it possible to query this somehow? If all else fails I can play the clip programatically and time it, but I would prefer a more direct method if possible. Thanks!
I don't know if this is fast enough for you. But in case you don't know - you don't have to actually play it. It is enough to create MediaPlayer instance and set the path of the file and the call getDuration().
MediaPlayer mp = MediaPlayer.create(yourActivity, Uri.parse(path));
int duration = mp.getDuration();
I do this by using my input stream: is.available() on InputStream is gives me the length.

Determining the duration and format of an audio file

Given a path (on the SD card) to an audio file, what is the best way of determining the length of the audio in milliseconds and the file format (or Internet media type)?
(For the duration one could use MediaPlayer's getDuration-method, but this seems too slow/clumsy.)
For the length of the audio file:
File yourFile;
MediaPlayer mp = new MediaPlayer();
FileInputStream fs;
FileDescriptor fd;
fs = new FileInputStream(yourFile);
fd = fs.getFD();
mp.setDataSource(fd);
mp.prepare();
int length = mp.getDuration();
mp.release();
Check this for MimeType:
https://stackoverflow.com/a/8591230/3937699
I think the easiest way is:
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(uriOfFile);
int duration = mp.getDuration();
mp.release();
/*convert millis to appropriate time*/
return String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
);
Just taking a stab at an answer for you, but you could probably determine the media type by the file extension - which I think MediaFile may be able to help you with. As for duration, I believe the getDuration() method is actually a native call, so I don't know if you will be able to do it much faster.

Categories

Resources