Alex Crow
Alex Crow

Reputation: 439

Get bitrate os audio item swift

I need to get an Audio Item (remote) bitrate - 320, 128, etc. Found an answer - How to get an MP3 bit rate in SWIFT, but it doesn't work correctly. I can get a size of item, but my bitrate looks weird - like 154, 540.34, etc. Help pls!

Upvotes: 2

Views: 1645

Answers (2)

Alex Crow
Alex Crow

Reputation: 439

I've found solutions: 1. For local file:

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. For URL remote file:

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

Upvotes: 1

Sanchit Kumar Singh
Sanchit Kumar Singh

Reputation: 513

AVPlayer requires AVPlayerItem, which in your case is a MP3 file. AVFoundation has a class AVPlayerItemAccessLogEvent which can provide you with AverageAudioBitrate. So, you have to pass your AVPlayerItem to the following function:

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;
    }

Since the APIs are exposed by apple,I think this might solve your problem.

Upvotes: 0

Related Questions