2017-06-06 82 views
2

我正在嘗試將我的音頻播放器中的網址轉換爲AVAsset,以便我能夠按照自己的喜好操作音軌。 (我只是想能夠修剪文件)。不幸的是,我遇到了資產轉換不正確的問題。當我在轉換音頻網址之前打印音頻網址的持續時間時,它會正確輸出持續時間。不幸的是,當我將它轉換爲AVAsset時,它說持續時間爲0.發生了什麼?任何指導將非常感謝!將URL轉換爲AVAsset - Swift

func trimmingFunc() { 

     try? audioPlayer = AVAudioPlayer(contentsOf: audioURL!) 
     passingTime = audioPlayer.duration 
     audioPlayer.delegate = self 


     let currentDuration = audioPlayer.duration 
     print(currentDuration) //correctly prints duration 
     let filePath = URL(fileURLWithPath: (("\(String(describing: audioPlayer.url!))"))) 
     print(filePath) //correctly prints filePath 


     let currentAsset = AVAsset(url: filePath) 
     print(CMTimeGetSeconds(currentAsset.duration) //This is printing 0 

} 
+0

'由於定時視聽媒體的性質,在資產成功初始化後,其鍵值的部分或全部值可能不會立即可用。「(https://developer.apple.com/documentation/avfoundation/ avasset) –

+0

因此,這意味着我需要計算持續時間和修剪/操作完成處理程序中的音頻文件? B/C從多個例子中看到的(不是他們爲我工作)是他們在完成處理程序之前計算信息。 – AndrewS

+0

你可以使用KVO('[_currentAsset addObserver:self forKeyPath:@「duration」'''observeValueForKeyPath') –

回答

2

加載一個AVAsset是異步操作。你應該等到它準備好。 「等待」的最有效方式是使用KVO。

在你的類,讓它成爲ViewController,使AVAsset成員,並致電trimmingFunc地方:

​​

在你trimmingFunc認購currentAsset通知:

func trimmingFunc() { 

    let audioURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "Be That Man", ofType: "mp3")!) 

    print("audioURL=\(audioURL)") 
    currentAsset = AVAsset(url: audioURL) 
    let options = NSKeyValueObservingOptions([.new, .old, .initial, .prior]) 
    currentAsset!.addObserver(self, forKeyPath: "duration", options: options, context: nil) 
} 

要接收該通知,覆蓋功能observeValueNSObject

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 

    print("\(keyPath): \(change?[.newKey])") 

    print(CMTimeGetSeconds(currentAsset!.duration)) //This is printing 0 
} 

所以,如果你有文件「是Man.mp3」在資源,幾毫秒後,你會看到持續時間=視圖控制器的202.945306122449

的完整代碼here

+0

爲什麼這會成爲可選項? '可選(「持續時間」):可選(<00000000 00000000 01000000 01000000 00000000 00000000>)我的持續時間結束爲0 – AndrewS

+0

它正確地打印出URL – AndrewS