2012-01-27 73 views
11

我使用此代碼player.duration顯示的MPMoviePlayerController始終爲零的視頻文件

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] 
            initWithContentURL:[NSURL fileURLWithPath:videostr]]; 

其中videostr是視頻文件的路徑打起了小視頻mpmediaplayer控制器。

現在我需要獲得該視頻文件的長度,因爲我使用此代碼。

length = player.duration; 

但它始終顯示爲0.000。但視頻播放良好。

我通過使用Google搜索每個地方檢查代碼來獲得視頻持續時間只有player.duration

,我嘗試一些其他的代碼也

AVURLAsset *asset = [[[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videostr] 
              options:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], AVURLAssetPreferPreciseDurationAndTimingKey, nil]] autorelease]; 
NSTimeInterval duration; 
if (asset) 
    duration = CMTimeGetSeconds(asset.duration) ; 
NSLog(@">>>>>>>>>>>>>>>>>>>> %f", asset.duration); 

即使它顯示zero.Can任何一個請幫助我。

提前致謝。

回答

22

在內容實際可播放之前,您無法獲得有用的持續時間。

註冊負載狀態的變化:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(MPMoviePlayerLoadStateDidChange:) 
              name:MPMoviePlayerLoadStateDidChangeNotification 
              object:nil]; 

評估一旦被通知的狀態:

- (void)MPMoviePlayerLoadStateDidChange:(NSNotification *)notification 
{ 
    if ((player.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK) 
    { 
     NSLog(@"content play length is %g seconds", player.duration); 
    } 
} 
+0

通知:MPMoviePlayerLoadStateDidChangeNotification 調用2次automatiaclly – g212gs 2014-06-28 09:00:21

+0

如果默認視頻暫停,則此解決方案不起作用,因爲當用戶執行播放操作時會調用此通知。以任何方式獲得持續時間? – jose920405 2015-06-24 14:15:13

2

SWIFT

可以在迅速做這樣

func getMediaDuration(url: NSURL!) -> Float64{ 
     var asset : AVURLAsset = AVURLAsset.assetWithURL(url) as AVURLAsset 
     var duration : CMTime = asset.duration 

     return CMTimeGetSeconds(duration) 
    } 
1

使用MPMovieDurationAvailableNotification

[[NSNotificationCenter defaultCenter] addObserver:self 
            selector:@selector(movieDurationAvailable:) 
             MPMovieDurationAvailableNotification object:nil]; 

- (void)movieDurationAvailable:(NSNotification *)notification { 

     NSLog(@"content play length is %g seconds", moviePlayer.duration); 


} 
+1

也許擴大一點這個答案。用代碼示例或其他有用的東西.... – 2015-03-30 20:27:52

+0

只有當用戶執行播放動作 – jose920405 2015-06-24 14:17:26

0

你可以從視頻文件中使用下面的代碼獲取持續時間。

NSURL *videoURL = [NSURL fileURLWithPath:VideoFileURL]; 

AVURLAsset *sourceAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil]; 

CMTime duration = sourceAsset.duration; 

double durationInSeconds = duration.value/duration.timescale; 

durationInSeconds變量你會得到確切的持續時間,以秒爲單位。