Niek van der Steen
Niek van der Steen

Reputation: 1433

iOS: How to get Audio Sample Rate from AVAsset or AVAssetTrack

After loading an AVAsset like this:

AVAsset *asset = [AVAsset assetWithURL:url];

I want to know what the Sampling Rate is of the Audio track. Currently, I am getting the Audio Track like this:

AVAssetTrack *audioTrack = [[asset tracksWithMediaCharacteristic:AVMediaCharacteristicAudible] objectAtIndex:0];

Which works. But I can't seem to find any kind of property, not even after using Google ;-) , that gives me the sampling rate. How does this work normally ? Is it even possible ? (I start doubting more and more, because Googling is not giving me a lot of information ...)

Upvotes: 6

Views: 5825

Answers (4)

Fox Ha
Fox Ha

Reputation: 21

private func getFormat(localUrl:String)->[String: Any?]{
    let audioUrl = URL.init(string: localUrl)
    let file=try! AVAudioFile(forReading: audioUrl!)
    let format=file.fileFormat
    return [
        "sampleRate":format.sampleRate,
        "channelCount":format.channelCount
    ]
}

Upvotes: 0

MrPOHB
MrPOHB

Reputation: 31

Using Swift and AVFoundation :

let url = Bundle.main.url(forResource: "audio", withExtension: "m4a")!
let asset = AVAsset(url: url)
if let firstTrack = asset.tracks.first {
    print("bitrate: \(firstTrack.estimatedDataRate)")
}

To find more information in your metadata, you can also consult: https://developer.apple.com/documentation/avfoundation/avassettrack https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/finding_metadata_values

Upvotes: 1

Pescolly
Pescolly

Reputation: 942

let asset = AVAsset(url: URL(fileURLWithPath: "asset/p2a2.aif"))
let track = asset.tracks[0]
let desc = track.formatDescriptions[0] as! CMAudioFormatDescription
let basic = CMAudioFormatDescriptionGetStreamBasicDescription(desc)
print(basic?.pointee.mSampleRate)

I'm using Swift so it looks a bit different but it should still work with Obj-C.

print(track.naturalTimeScale)

Also seems to give the correct answer but I'm a bit apprehensive because of the name.

Upvotes: 9

Niek van der Steen
Niek van der Steen

Reputation: 1433

Found it. I was using the MTAudioProcessingTap, so in the prepare() function I could just use:

void prepare(MTAudioProcessingTapRef tap, CMItemCount maxFrames, const AudioStreamBasicDescription *processingFormat)
{
    sampleRate = processingFormat->mSampleRate;
    NSLog(@"Preparing the Audio Tap Processor");
}

Upvotes: 0

Related Questions