2013-02-07 102 views
19

我需要獲取(本地)視頻的持續時間,然後才能訪問其各個幀,如UIImage s。到目前爲止,我一直在使用MPMoviePlayerControlleriOS:獲取視頻持續時間和縮略圖而不播放視頻

首先我註冊了MPMovieDurationAvailableNotification事件,然後撥打prepareToPlay。當收到事件時,我注意到視頻的持續時間,然後我通過requestThumbnailImagesAtTimes請求幀。

這可以工作,但是即使我沒有以任何方式將視頻添加到視圖(我可以聽到在後臺播放的音頻),視頻似乎也開始播放。

有沒有什麼方法可以在沒有實際播放視頻的情況下獲得視頻的持續時間和幀數?

+0

如果要存儲在視頻文件系統,那麼你可以作爲[AVAsset]來訪問它(https://developer.apple.com/library/mac/#documentation/AVFo undation/Reference/AVAsset_Class/Reference/Reference.html)assetWithUrl:並且返回的AVAsset具有持續時間屬性。不知道有關縮略圖。 – geraldWilliam

+0

關於這個問題的任何建議:https://stackoverflow.com/questions/47617130/error-getting-same-video-thumbnail-image-every-time-in-swift3-ios/47617794#47617794 –

回答

35

要獲取持續時間:

NSURL *sourceMovieURL = [NSURL fileURLWithPath:somePath]; 
AVURLAsset *sourceAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil]; 
CMTime duration = sourceAsset.duration; 

要獲得framegrab:

AVAssetImageGenerator* generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:destinationAsset]; 

//Get the 1st frame 3 seconds in 
int frameTimeStart = 3; 
int frameLocation = 1; 

//Snatch a frame 
CGImageRef frameRef = [generator copyCGImageAtTime:CMTimeMake(frameTimeStart,frameLocation) actualTime:nil error:nil]; 
+0

這確實得到了正確的時間,謝謝。然而,「搶框」時機似乎有點關閉。我不得不使用CMTimeMakeWithSeconds(offsetInSeconds,600)。 –

+0

什麼是frameTime?我看到frameTimeStart,應該是frameTime嗎? – etayluz

+1

好趕上@etayluz – Shizam

6

調用setShouldAutoPlay:NO確實與在的MPMoviePlayerController招:

moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL: movieURL]; 
[moviePlayerController setShouldAutoplay:NO]; 
[moviePlayerController prepareToPlay]; 

編輯:我越來越不解釋downvoted,但我會通過這個答案站立。如果您需要使用MPMoviePlayerController,那麼這將阻止媒體的自動播放,但仍然可以按照我的原始問題獲取持續時間和縮略圖。

+0

其他人是否同意將自動播放設置爲TRUE作爲默認設置很愚蠢? – sunny

+1

你的答案的確是,呃,回答這個問題;但我猜你會被拒絕投票,因爲你使用'MPMoviePlayerController'所做的是一個醜陋的解決方法,可能會使用比獲取所需信息所需資源更多的資源,並可能會在未來的iOS版本中崩潰。你要求系統加載到內存,並準備播放視頻,只需要一些關於它的元數據即可。 偏題:只是出於好奇,它顯示你誰投票給你嗎?我從來沒有投過票,所以我很好奇。 – Velociround

8

可以在迅速得到這樣

func getMediaDuration(url: NSURL!) -> Float64{ 
    let asset : AVURLAsset = AVURLAsset(URL: url) as AVURLAsset 
    let duration : CMTime = asset.duration 
    return CMTimeGetSeconds(duration) 
} 
+0

請檢查此:https://stackoverflow.com/questions/47617130/error-getting-same-video-thumbnail-image-every-time-in-swift3-ios –