【问题标题】:Converting URL to AVAsset - Swift将 URL 转换为 AVAsset - Swift
【发布时间】:2017-06-06 12:29:59
【问题描述】:

我正在尝试将我的音频播放器中的 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

}

【问题讨论】:

  • Because of the nature of timed audiovisual media, upon successful initialization of an asset some or all of the values for its keys may not be immediately available. (developer.apple.com/documentation/avfoundation/avasset)
  • 这是否意味着我需要在完成处理程序中计算持续时间并修剪/操作我的音频文件? B/C 我从多个示例中看到的(不是它们对我有用)是它们在完成处理程序之前计算信息。
  • 你可以使用 KVO ([_currentAsset addObserver:self forKeyPath:@"duration" + observeValueForKeyPath )

标签: swift string swift3 xcode8 avaudioplayer


【解决方案1】:

加载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)
}

要接收该通知,请覆盖 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
}

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

ViewController 的完整代码是here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多