swift - 将 URL 转换为 AVAsset - Swift

标签 swift string swift3 xcode8 avaudioplayer

我正在尝试将我的音频播放器中的 url 转换为 AVAsset,以便我能够根据自己的喜好操作音轨。 (我只想能够修剪文件)。不幸的是,我遇到了 Assets 未正确转换的问题。当我在转换之前打印音频 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

}

最佳答案

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

在你的类中,让它成为ViewController,让AVAsset成为成员并在某处调用你的trimmingFunc:

class ViewController: UIViewController {

    var currentAsset: AVAsset?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.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)
}

要接收通知,重写 NSObject 的函数 observeValue:

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
}

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

ViewController 的完整代码是 here .

关于swift - 将 URL 转换为 AVAsset - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44390046/

相关文章:

ios - 如何快速呈现来自 UICollectionView 的 activityViewController

javascript - 如何 chop 段落第一行之后的字符串

ios - Xcode 8 中没有这样的模块 'CryptoSwift'

ios - 如何将 NSData 参数传递给 swift 3 中调用的 objective-c 方法?

ios - 下拉刷新时 UITableview 出错,所有数据重复出现。任何人都可以帮助使用 Swift3 , Xcode8

swift - 如何从函数中取出纬度和经度的值,以便它们可以在 VC 中的其他任何地方使用?

ios - 在 Swift 中循环遍历嵌入式 JSON 数组?

ios - 如何解决 NSScanner 上的 "Undefined symbols for architecture x86_64"问题? React-Native 中的 Swift pod

java - 在每个单词后打印空格

objective-c - 目标 - C : Combine multiple string arrays