How to retrieve Youtube Video Length in android? - android

In my app i have youtube video url. Now how can i get the duration of video from that url?
I used this code but it doesn't work. Any other way to get the video duration?
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource("https://www.youtube.com/watch?v=" + videoID);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInmillisec = Long.parseLong(time);
long duration = timeInmillisec / 1000;
long hours = duration / 3600;
long minutes = (duration - hours * 3600) / 60;
long seconds = duration - (hours * 3600 + minutes * 60);
Toast.makeText(this, "https://www.youtube.com/watch?v=" + videoID + "\n" + hours + " : " + minutes + " : " + seconds, Toast.LENGTH_SHORT).show();

if you have a youtube player instantiated with this id you can get the video duration from him.
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.loadVideo(videoID);
this.youtubePlayer=youTubePlayer;
}
}
and then you can do
youtubePlayer.getDurationMillis()
to get total video's time. Note that it will return 0 when video is loading so you might need to watch the evolution of the value returned and wait for it.
regards,

Related

How to display Time in appropriate way ( Min:Sec)?

I'm coding a media player app but the Time (for seekbar) appears incorrectly. Is there an error in calculation? How can I adjust the Time in the code?
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
You are calculating the seconds incorrectly. You need to multiply the minutes by 60 and then subtract it from total seconds to get the seconds in this minute.
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) - 60 * TimeUnit.MILLISECONDS.toMinutes(realtimeLength)
This should work.
You should use Debugger to try to debug why your output is incorrect.
Please pass duration in below method & it will give you formatted result back.
long secs = mediaPlayer.getDuration()/1000;
public String makeShortTimeString(final Context context, long secs) {
long hours, mins;
hours = secs / 3600;
secs %= 3600;
mins = secs / 60;
secs %= 60;
String durationFormat = context.getResources().getString(
hours == 0 ? R.string.durationformatshort : R.string.durationformatlong);
return String.format(durationFormat, hours, mins, secs);
}
where durationformatshort = %2$d:%3$02d
and durationformatlong = %1$d:%2$02d:%3$02d

Problems creating timer in android

I am trying to build a timer that counts down in seconds and updates a TextView every time so it shows the time remaining. From what I can tell the timer code is working fine (1 second between events and converts from hrs and mins to secs fine) cause I have tested it outside of Android and using Log.d() in android. Updating the textview is whats giving me problems. I was getting null pointers when originally trying to update the textview cause only the UI thread can access the UI(my interpretation of the error message) and I added the runOnUiThread() which allows it to be accessed and updated but it now doesn't update correctly. I think this is where the problem lies but I am not totally sure and don't know enough to figure out how to fix it or come up with a better way to do this. I would appreciate another set of eyes. Thanks
final static int delay = 1000;
final static int period = 1000;
public void start(int hin, int min) {
run = true;
int hrinsec = (hin * (60 * 60));
int mininsec = (min * 60);
secs = hrinsec + mininsec;
run = false;
interval = secs;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Convert seconds back to hrs and mins
hrsFromSecs(secs);
minsFromSecs(secs);
secsFromSecs(secs);
dint total = hours + minutes + seconds;
output = hours + " Hours " + minutes + " Minutes " + seconds
+ " Seconds";
// Countdown and update the textview
runOnUiThread(new Runnable() {
#Override
public void run() {
timer.setText(output);
}});
secs = secs - 1;
checkIfDone(total);
}
}, delay, period);
}
Use CountDownTimer no need to reinvent anything

Android get the selected audio file's duration from storage [duplicate]

How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);

Android rolling digital time display wanted

I'm looking for Android code to do a digital timer display that looks like one of the standard timers that came (I think) with some HTC phones. The timer look is different than most in that it uses digits but has a mechanical scroll wheel look, as if the numbers were painted on a roller. It does not mimic an LED timer nor does it mimic a mechanic "flip" type digital timer. It may need graphic files to work.
There is code on googlesource that seems it may have what I want. But I can't find any index that has images of the code running. And it is not always easy (for me) to get the code running so I can see what it looks like. Some code that looks promising is the following:
(https://android.googlesource.com/device/htc/common/)
http://st.gsmarena.com/vv/reviewsimg/htc-droid-incredible-4g-lte/sshots/gsmarena_109.jpg">Link to image</a>">
See http://code.google.com/p/android-wheel/
You might be able to adapt it for your needs.
Here's code provided by a previous user:
private Handler mHandler = new Handler();
OnClickListener mStartListener = new OnClickListener()
{
public void onClick(View v)
{
if (mStartTime == 0L)
{
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
.........
private Runnable mUpdateTimeTask = new Runnable()
{
public void run()
{
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10)
{
mTimeLabel.setText("" + minutes + ":0" + seconds);
}
else
{
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
}
};
https://stackoverflow.com/users/559090/khawar

Get mp3 duration in android

How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);

Categories

Resources