2

I am searching for a way of getting an mp3 bitrate like 128kbps or 320kbps for mp3 audio from url link.

I have a UITableView that loads a list of files from url list, and I would like to display an audio quality. I have tried using AVAudioPlayer and AVPlayer but no luck. Please help, how can I achieve this?

 do{
       let audioPlayer = try AVAudioPlayer(contentsOf:audioURL)
       print(audioPlayer.settings)
       if #available(iOS 10.0, *) {
                print(audioPlayer.format)
            } else {
                // Fallback on earlier versions
            }
        }catch {
            print("Error getting the audio file")
        }
Janmenjaya
  • 4,149
  • 1
  • 23
  • 43
Yaroslav Dukal
  • 3,894
  • 29
  • 36

3 Answers3

1

Just using the formula. It was that easy..

var bitrate: Int {      // kbps
        if size > 0 && duration > 0 {
            return size * 8 / 1000 / duration
        }
Yaroslav Dukal
  • 3,894
  • 29
  • 36
0

I found a variable name sampleRate of AVAudioFormat class. Did you try to call audioPlayer.format.sampleRate?

Hieu Dinh
  • 692
  • 5
  • 18
0

Extension

import AVFoundation

extension AVURLAsset {

    var fileSize : Int? {
        
        let keys: Set<URLResourceKey> = [.totalFileSizeKey, .fileSizeKey]
        let resourceValues = try? url.resourceValues(forKeys: keys)

        return resourceValues?.fileSize ?? resourceValues?.totalFileSize

    }
    
    // kbps
    
    var bitrate : Int {

        if (fileSize ?? 0) > 0 && duration.seconds > 0 {

            return Int(Double(fileSize ?? 0) * 8 / 1000 / duration.seconds)

        }
        
        return 0
        
    }

}

Usage

// bitrate
    
let avAsset = AVURLAsset.init(url: mp3Url)
    
let bitrate = avAsset.bitrate
print("avAsset.bitrate: \(bitrate)")
Michael N
  • 436
  • 5
  • 6