开发者

Extract only some part (duration) from a string

I used the following command to find the duration of an mp3 file:

$ ffmpeg -i audiofile.mp3 2>&1 | grep 开发者_如何学GoDuration

Duration: 01:02:20.20, start: 0.000000, bitrate: 128 kb/s

How can extract the Duration time (01:02:20.20) from the above result with Java code(method)?

Thanks in advance

Antonis


If you are running this command through Runtime.exec or ProcessBuilder then you could just run:

ffmpeg -i audiofile.mp3 2>&1 | grep Duration | cut -d, -f1 | cut -d' ' -f2

to get the duration straightaway, instead of doing parsing in Java.


String str = Duration: 01:02:20.20, start: 0.000000, bitrate: 128 kb/s

int startIndex = str.indexOf(":");  
int endIndex = str.indexOf(",");

str.subString(startIndex,endIndex); //your result  
str.trim();

Note: assumption is that the format will remain same


Regular expressions would be a good place to start.


I love String.split :)

String duration = result.split("[ ,]")[1];

This splits on space or comma.


If you want to use the time in calculations, you'll need to parse the constituent parts.

String string = "Duration: 01:02:20.20, start: 0.000000, bitrate: 128 kb/s";

// This expects 3 millisecond digits, as specified by [ffmpeg docs]*, though
// sample only has 2... maybe it's variable - adjust as needed
Pattern p = Pattern.compile("([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]{3}))?");
Matcher m = p.matcher(string);

if (m.find()) {
    int h = Integer.parseInt(m.group(1));
    int m = Integer.parseInt(m.group(2));
    int s = Integer.parseInt(m.group(3));
    int ms = Integer.parseInt(m.group(4));
    // do some time math
}

ffmpeg docs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜