将 URL 转换为 AVAsset - Swift

And*_*ewS 6 string avaudioplayer swift swift3 xcode8

我正在尝试将音频播放器中的 url 转换为 AVAsset,以便我能够根据自己的喜好操纵音轨。(我只想能够修剪文件)。不幸的是,我遇到了资产未正确转换的问题。当我在转换之前打印音频 url 的持续时间时,它会正确打印出持续时间。不幸的是,当我将其转换为 AVAsset 时,它说持续时间为 0。这是怎么回事?任何指导将不胜感激!

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

}
Run Code Online (Sandbox Code Playgroud)

Olh*_*iuk 6

加载一个AVAsset是异步操作。你应该等到它准备好了。“等待”的最有效方法是使用 KVO。

在你的类,让它成为ViewController,使AVAsset会员和打电话给你的trimmingFunc地方:

class ViewController: UIViewController {

    var currentAsset: AVAsset?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.trimmingFunc()
    }
....
Run Code Online (Sandbox Code Playgroud)

在您的 中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)
}
Run Code Online (Sandbox Code Playgroud)

要收到通知,覆盖功能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
}
Run Code Online (Sandbox Code Playgroud)

所以,如果你在资源中有“Be That Man.mp3”文件,几毫秒后你会看到持续时间 = 202.945306122449

ViewController 的完整代码在这里