Как получить длительность видео с помощью xuggler

Этот код считывает длительность времени в long, но когда он конвертируется в дату с форматом времени 'чч: мм: сс', он дает другое значение, а продолжительность видео составляет 00:08:07. что не так в этом коде

String filename = "C:\\Documents\\Airtel Youthstar-Tutorial.mp4";   
    IContainer container = IContainer.make();  
    int result = container.open(filename, IContainer.Type.READ, null);  
    long duration = container.getDuration();  
    System.out.println("Duration (ms): " + duration);  

4 ответа

Решение

Я получил правильную продолжительность видео, используя IBMPlayerForMpeg4SDK-1.0.0.jar, и его работа меня устраивает, используя следующий код

/**
     * 
     * @param filename is the video full file path stored at any location of the system 
     * @return the value containing the time format of the video file
     */
    public static String getDurationInString(String filename)
    {
        try {
            //
            long ms=getDuration(new File(filename));
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(ms),
                    TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
                    TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
            //System.out.println(hms);
            return hms;
        } catch (IOException ex) {
            Logger.getLogger(VideoInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }


    /**
     * 
     * @param file : file that specify the file in the File location
     * @return the duration in long 
     * @throws IOException if any exception is thrown by the system 
     */
    public static long getDuration(File file) throws IOException {
        PlayerControl playerControl = PlayerFactory.createLightweightMPEG4Player();
        playerControl.open(file.getAbsolutePath());
        return playerControl.getDuration();
    }

На самом деле ваш код возвращает время в микросекундах. Если вы хотите получить java.util.Duration, вы должны использовать:

public static Duration getVideoDuration(String videoPath) {
    IContainer container = IContainer.make();
    int result = container.open(videoPath, IContainer.Type.READ, null);
    long durationInMicrosec = container.getDuration();
    long durationInNanoSec = durationInMicrosec * 1000;     
    return Duration.ofNanos(durationInNanoSec);
}

И для форматирования времени результата вы можете использовать код из @SASM, и ввод для его кода должен быть

long ms = getVideoDuration("your_path_here").toMillis()

Если вы получите продолжительность в milliseconds

long ms = xxxxx;

Вы можете преобразовать его в hh:mm:ss формат как показано ниже:

String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(ms),
        TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
        TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
System.out.println(hms);
//In order to import you need to get mp4parser from here: https://github.com/sannies/mp4parser
//imports
import com.coremedia.iso.IsoFile;

//get the duration of video
    private double GetVideoDuration () throws IOException {
        double DurationVideo = 0;
        //pathPlaying is a string this format: "src/videos/video.mp4"
        IsoFile isoFile = new IsoFile(pathPlaying);
        DurationVideo = (double)
                isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
        return DurationVideo;
    }
Другие вопросы по тегам