ios 在objective-c中将CMTime转换为人类可读的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10654750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:26:56  来源:igfitidea点击:

Converting CMTime to human readable time in objective-c

objective-ciosccocoa-touchcmtime

提问by randomor

So I have a CMTime from a video. How do I convert it into a nice string like in the video time duration label in the Photo App. Is there some convenience methods that handle this? Thanks.

所以我有一个来自视频的 CMTime。如何将其转换为像 Photo App 中的视频持续时间标签那样的漂亮字符串。有没有一些方便的方法来处理这个问题?谢谢。

AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:url options:nil];
CMTime videoDuration = videoAsset.duration;
float videoDurationSeconds = CMTimeGetSeconds(videoDuration);

采纳答案by Andreyz4k

For example you can use NSDate and it's description method. You can specify any output format you want.

例如,您可以使用 NSDate 及其描述方法。您可以指定所需的任何输出格式。

> ` 
// First, create NSDate object using 
NSDate* d = [[NSDate alloc] initWithTimeIntervalSinceNow:seconds]; 
// Then specify output format 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH:mm:ss"]; 
// And get output with 
NSString* result = [dateFormatter stringWithDate:d];`

回答by ceekay

You can use this as well to get a video duration in a text format if you dont require a date format

如果您不需要日期格式,您也可以使用它来获取文本格式的视频时长

AVURLAsset *videoAVURLAsset = [AVURLAsset assetWithURL:url];
CMTime durationV = videoAVURLAsset.duration;

NSUInteger dTotalSeconds = CMTimeGetSeconds(durationV);

NSUInteger dHours = floor(dTotalSeconds / 3600);
NSUInteger dMinutes = floor(dTotalSeconds % 3600 / 60);
NSUInteger dSeconds = floor(dTotalSeconds % 3600 % 60);

NSString *videoDurationText = [NSString stringWithFormat:@"%i:%02i:%02i",dHours, dMinutes, dSeconds];

回答by Lifely

You can use CMTimeCopyDescription, it work really well.

你可以使用CMTimeCopyDescription,它工作得很好。

NSString *timeDesc = (NSString *)CMTimeCopyDescription(NULL, self.player.currentTime);
NSLog(@"Description of currentTime: %@", timeDesc);

edit:okay, i read the question too fast, this is not what your wanted but could be helpful anyway for debuging.

编辑:好的,我阅读问题的速度太快了,这不是您想要的,但无论如何可能对调试有帮助。

edit:as @bcattle commented, the implementation i suggested contain a memory leak with ARC. Here the corrected version :

编辑:正如@bcattle 所评论的,我建议的实现包含 ARC 的内存泄漏。这里是更正的版本:

NSString *timeDesc = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, self.player.currentTime));
NSLog(@"Description of currentTime: %@", timeDesc);

回答by Brody Robertson

Based on combination of the question and comments above, this is concise:

基于以上问题和评论的结合,这是简洁的:

AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:url options:nil];
CMTime videoDuration = videoAsset.duration;
float videoDurationSeconds = CMTimeGetSeconds(videoDuration);

NSDate* date = [NSDate dateWithTimeIntervalSince1970:videoDurationSeconds];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"HH:mm:ss"];  //you can vary the date string. Ex: "mm:ss"
NSString* result = [dateFormatter stringFromDate:date];

回答by codingrhythm

There is always an extension ;)

总有一个扩展名 ;)

import CoreMedia

extension CMTime {
    var durationText:String {
        let totalSeconds = Int(CMTimeGetSeconds(self))
        let hours:Int = Int(totalSeconds / 3600)
        let minutes:Int = Int(totalSeconds % 3600 / 60)
        let seconds:Int = Int((totalSeconds % 3600) % 60)

        if hours > 0 {
            return String(format: "%i:%02i:%02i", hours, minutes, seconds)
        } else {
            return String(format: "%02i:%02i", minutes, seconds)
        }
    }
}

to use

使用

videoPlayer?.addPeriodicTimeObserverForInterval(CMTime(seconds: 1, preferredTimescale: 1), queue: dispatch_get_main_queue()) { time in
    print(time.durationText)
}

回答by user3069232

Swift 3.0 ios 10 answer based codingrhythmanswer...

Swift 3.0 ios 10 answer based codingrhythmanswer...

extension CMTime {
var durationText:String {
    let totalSeconds = CMTimeGetSeconds(self)
    let hours:Int = Int(totalSeconds / 3600)
    let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
    let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))

    if hours > 0 {
        return String(format: "%i:%02i:%02i", hours, minutes, seconds)
    } else {
        return String(format: "%02i:%02i", minutes, seconds)
    }
  }
}

回答by Timur Bernikovich

Simple extension I use for displaying video file duration.

我用于显示视频文件持续时间的简单扩展。

import CoreMedia

extension CMTime {
    var stringValue: String {
        let totalSeconds = Int(self.seconds)
        let hours = totalSeconds / 3600
        let minutes = totalSeconds % 3600 / 60
        let seconds = totalSeconds % 3600 % 60
        if hours > 0 {
            return String(format: "%i:%02i:%02i", hours, minutes, seconds)
        } else {
            return String(format: "%02i:%02i", minutes, seconds)
        }
    }
}

回答by Nik Kov

Swift 4.2 extension

斯威夫特 4.2 扩展

extension CMTime {
    var timeString: String {
        let sInt = Int(seconds)
        let s: Int = sInt % 60
        let m: Int = (sInt / 60) % 60
        let h: Int = sInt / 3600
        return String(format: "%02d:%02d:%02d", h, m, s)
    }

    var timeFromNowString: String {
        let d = Date(timeIntervalSinceNow: seconds)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "mm:ss"
        return dateFormatter.string(from: d)
    }
}

回答by Asad Amodi

here is the code for getting seconds from cmtime

这是从 cmtime 获取秒数的代码

NSLog(@"seconds = %f", CMTimeGetSeconds(cmTime));

回答by Ravi Sharma

A simplest way (without using NSDate and NSDateFormatter) to do this:-

一个最简单的方法(不使用 NSDate 和 NSDateFormatter)来做到这一点:-

Using Swift:-

使用 Swift:-

        func updateRecordingTimeLabel()
        {

    // Result Output = MM:SS(01:23) 
    let cmTime = videoFileOutput.recordedDuration
                    var durationInSeconds = Int(CMTimeGetSeconds(cmTime))
                    let durationInMinutes = Int(CMTimeGetSeconds(cmTime)/60)
                    var strDuMin = String(durationInMinutes)

                    durationInSeconds = durationInSeconds-(60*durationInMinutes)
                    var strDuSec = String(durationInSeconds)

                    if durationInSeconds < 10
                    {
                        strDuSec = "0"+strDuSec
                    }
                    if durationInMinutes < 10
                    {
                        strDuMin = "0"+strDuMin
                    }
    // Output string
     let str_output = strDuMin+":"+strDuSec
print("Result Output : [\(str_output)]")

}