得到比特率的音频项目迅速

时间:2017-04-29 08:12:12

标签: ios swift avfoundation media-player

我需要获得音频项目(远程)比特率 - 320,128等。找到答案 - How to get an MP3 bit rate in SWIFT,但它无法正常工作。我可以得到一个大小的项目,但我的比特率看起来很奇怪 - 像154,540.34等。 请帮忙!

2 个答案:

答案 0 :(得分:1)

我找到了解决方案: 1.对于本地文件:

func getSongBitrate(audioURL: URL, duration: Int, completition: @escaping (Int) -> ()) {
    do {
        let attr = try FileManager.default.attributesOfItem(atPath: audioURL.path)

        if var fileSize = attr[FileAttributeKey.size] as?  UInt64 {
            let dict = attr as NSDictionary
            fileSize = dict.fileSize()

            let kbit = fileSize/128//calculate bytes to kbit
            let kbps = ceil(round(Double(kbit)/Double(duration))/16)*16
            completition(Int(kbps))
        }
    } catch {
        print("Error: \(error)")
        completition(Int(0))
    }
}
  1. 对于URL远程文件:

    func getBitrate(audioURL: URL, duration: Int, completition: @escaping (Int) -> ()) {
    
        DispatchQueue.global().async {
            let request1: NSMutableURLRequest = NSMutableURLRequest(url: audioURL)
            request1.httpMethod = "HEAD"
    
            var response : URLResponse?
            print("GO TO RESPONSE")
            do {
                try NSURLConnection.sendSynchronousRequest(request1 as URLRequest, returning: &response)
    
                if let httpResponse = response as? HTTPURLResponse {
    
                    let size = httpResponse.expectedContentLength
                    let kbit = size/128;//calculate bytes to kbit
                    let kbps = ceil(round(Double(kbit)/Double(duration))/16)*16
    
                     // print("kbps === \(kbps)")
    
                    if self.songQuality == 0 {
                       self.songQuality = Int(kbps)
                   }
    
                    ////
    
                    DispatchQueue.main.async {
                        completition(Int(kbps))
                    }
    
                    ////
    
                }
    
            } catch (let e) {
                print(e)
                DispatchQueue.main.async {
                    completition(Int(0))
                }
            }
        }
    }
    

答案 1 :(得分:0)

AVPlayer需要AVPlayerItem,在您的情况下是一个MP3文件。 AVFoundation有一个AVPlayerItemAccessLogEvent类,它可以为您提供 AverageAudioBitrate 。因此,您必须将AVPlayerItem传递给以下函数:

func getBitRate(playerItem : AVPlayerItem) -> Double{
        //var event : AVPlayerItemAccessLogEvent;
        var avgBitrate : Double = 0.0;
        for event in (playerItem.accessLog()?.events)!{
            if event.averageAudioBitrate>=0.0{
                avgBitrate = event.averageAudioBitrate;
            }
        }
        return avgBitrate;
    }

由于API是苹果暴露的,我认为这可能会解决您的问题。