Search code examples
iosswiftavfoundationmedia-player

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!


Solution

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