Last active
October 8, 2016 06:37
-
-
Save shingohry/c11002561f188780d55c to your computer and use it in GitHub Desktop.
use AVAudioFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Open the file | |
NSError *error = nil; | |
AVAudioFile *audioFile = [[AVAudioFile alloc] | |
initForReading: fileURL | |
commonFormat: AVAudioPCMFormatFloat32 | |
interleaved: NO | |
error: &error]; | |
// Fetch and print basic info | |
NSLog(@“File URL: %@\n”, fileURL.absoluteString); | |
NSLog(@“File format: %@\n”, audioFile.fileFormat.description); | |
NSLog(@“Processing format: %@\n”, audioFile.processingFormat.description); | |
AVAudioFramePosition fileLength = audioFile.length; | |
NSLog(@“Length: %lld frames, %.3f seconds\n”, (longlong)fileLength, fileLength / audioFile.fileFormat.sampleRate); | |
// Create a buffer to read into | |
const AVAudioFrameCount kBufferFrameCapacity = 128 * 1024L; | |
AVAudioPCMBuffer *readBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat: | |
audioFile.processingFormat frameCapacity: kBufferFrameCapacity]; | |
// Read the file a buffer at a time to find the loudest sample | |
float loudestSample = 0.0f; | |
AVAudioFramePosition loudestSamplePosition = 0; | |
while (audioFile.framePosition < fileLength) { | |
AVAudioFramePosition readPosition = audioFile.framePosition; | |
if (![audioFile readIntoBuffer: readBuffer error: &error]) { | |
NSLog(@"failed to read audio file: %@", error); | |
return NO; | |
} | |
if (readBuffer.frameLength == 0) | |
break; // finished | |
} | |
// For each channel, check each audio sample | |
for (AVAudioChannelCount channelIndex = 0; | |
channelIndex < readBuffer.format.channelCount; ++channelIndex) { | |
float *channelData = readBuffer.floatChannelData[channelIndex]; | |
for (AVAudioFrameCount frameIndex = 0; | |
frameIndex < readBuffer.frameLength; ++frameIndex) { | |
float sampleAbsLevel = fabs(channelData[frameIndex]); | |
if (sampleAbsLevel > loudestSample) { | |
loudestSample = sampleAbsLevel; | |
loudestSamplePosition = readPosition + frameIndex; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment