OStack程序员社区-中国程序员成长平台

标题: ios - 获取音频持续时间字符串以 float 值 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:20
标题: ios - 获取音频持续时间字符串以 float 值

{
     duration = "00:06:29";
     id = 7;
}

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;

float value = [numberFormatter numberFromString:currentAutio.duration].floatValue;
NSLog(@"Current audio %f",value);

out 是 当前音频 0.0000

如何将持续时间字符串设为浮点值?



Best Answer-推荐答案


最简单的方法是

NSString *duration = @"00:06:29";
NSArray *array = [duration componentsSeparatedByString":"];

NSLog(@"Current hrs %ld",(long)[(NSString *)(array[0]) integerValue]);
NSLog(@"Current min %ld",(long)[(NSString *)(array[1]) integerValue]);
NSLog(@"Current sec %ld",(long)[(NSString *)(array[2]) integerValue]);

否则你也可以使用 NSDate & NSDateFormatter

编辑


使用 NSDate,注意小时部分不应超过 23 否则结果可能与预期不符。

NSString *duration = @"00:06:29";

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"HH:mm:ss";

NSDate *date = [formatter dateFromString:duration];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
NSLog(@"hrs %ld", (long)components.hour);
NSLog(@"min %ld", (long)components.minute);
NSLog(@"sec %ld", (long)components.second);

关于ios - 获取音频持续时间字符串以 float 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41329321/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4