2013-02-22 64 views
2

我有一個奇怪的問題,使用AVFoundation AVPlayer添加觀察者的邊界時間。macruby AVPlayer addBoundaryTimeObserverForTimes

player = AVPlayer.playerWithURL(NSURL.URLWithString(someurl)) 
player.play() 
player.addBoundaryTimeObserverForTimes([NSValue.valueWithCMTime(CMTimeMake(1,1))], queue: nil, usingBlock: -> { puts 'success' }) 

在XCode中執行此代碼時,在添加觀察者時調用匯編代碼,而控制檯中沒有錯誤。 有人遇到過這樣的問題嗎?

回答

-1

也許它確實需要一些隊列作爲參數

傳遞試試這個:

dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

[player addBoundaryTimeObserverForTimes:[NSValue.valueWithCMTime(CMTimeMake(1,1))] 
            queue: myQueue 
          usingBlock: -> { puts 'success' }]; 
+0

不,將nil傳遞給隊列會導致主隊列被使用,按照文檔 – gadu 2015-08-16 06:36:10

0

我使用它像這樣,它的工作原理:

__block AVPlayer* blockPlayer = self.player;  //player is already initialised and set up; 
__block id obs; 

// Setup boundary time observer to trigger when audio really begins, 
// specifically after 1/3 of a second playback 

obs = [self.player addBoundaryTimeObserverForTimes: @[[NSValue valueWithCMTime:CMTimeMake(1, 10)]] 
              queue:NULL 
             usingBlock:^{ 

              // Raise a notificaiton when playback has started 
              [[NSNotificationCenter defaultCenter] postNotificationName:PLAYBACK_STARTED_NOTIFICATION object:nil]; 

              // Remove the boundary time observer 
              [blockPlayer removeTimeObserver:obs]; 
             }]; 
0

如果您仔細閱讀文檔,您會看到此方法返回:

返回值: 您作爲參數傳遞給removeTimeObserver的不透明對象:停止觀察。

及更高版本:

必須,只要你想要的時間觀測到由玩家來調用保留返回值。此方法的每次調用應具有相應的調用來配對removeTimeObserver:

你的問題是,你沒有保留方法的返回值,你只是調用該方法,因此時間觀察者沒有被玩家調用。

使用__block變量實際上要低於這裏

player = AVPlayer.playerWithURL(NSURL.URLWithString(someurl)) 
player.play() 

__block id observer = player.addBoundaryTimeObserverForTimes([NSValue.valueWithCMTime(CMTimeMake(1,1))], queue: nil, usingBlock: -> 
{ 
    puts 'success' 
    player.removeTimeObserver(observer) // IMPORTANT, but careful. Read below* 
}) 

工作*:作爲蘋果強調,需要調用removeTimeObserver,這是很有道理的,以我的地方是在完成塊,但至少在Obj C和Swift以及大多數其他語言中,這會導致保留週期。你可以在Obj C和Swift中通過聲明觀察者和玩家block variables來解決這個問題,以便你可以從塊內部安全地引用它們。

如果你可以找到其他地方安全調用removeTimeObserver方法,那麼你不必擔心。

反正上面的代碼會在播放器進入歌曲/視頻1秒鐘時執行該塊。

還要注意的是:

AV基金會並不保證調用你的塊傳遞的每個區間或邊界。如果先前調用的塊的執行沒有完成,AV Foundation不會調用塊。因此,您必須確保您在該區域執行的工作不會對系統過度徵稅。

,我不認爲適用於你,但可以向別人誰已經添加了多個時間間隔/邊界。