IOS: Формат файла аудиозаписи
Я использую аудиозапись. Он отлично работает с форматами caf
и wave
. Но проблема в том, что размер файла слишком велик.
Итак, может ли кто-нибудь помочь мне записывать аудио с форматом, который также играл в размер окна и файла, немного ниже.
Код, который я пробовал, приведен ниже:
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.wave"];
NSLog(@"%@",soundFilePath);
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,
[NSNumber numberWithInt:8], AVLinearPCMBitDepthKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[audioRecorder prepareToRecord];
}
Ответы
Ответ 1
Я также пытался использовать AVAudioRecorder для записи звука в кодированном формате AAC, предпочтительно в файле .m4a. Я быстро смог получить код для записи в AAC внутри основного звукового файла (.caf), но я не мог заставить AVAudioRecorder правильно форматировать .m4a. Я как раз собирался переписать код записи в своем приложении, используя более низкий уровень Audio Units API, но вместо этого я поместил его на задний план и добавил в код для обработки общей аудио сессии. Как только это было настроено, я вернулся и попытался сохранить как .m4a, и он просто сработал.
Вот пример кода:
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSURL *tmpFileUrl = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:@"tmp.m4a"]];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithFloat:16000.0], AVSampleRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
nil];
NSError *error = nil;
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:tmpFileUrl settings:recordSettings error:&error];
[recorder prepareToRecord];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
[session setActive:YES error:nil];
[recorder record];
Затем, чтобы закончить запись, я использовал:
[recorder stop];
AVAudioSession *session = [AVAudioSession sharedInstance];
int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
[session setActive:NO withFlags:flags error:nil];
Тогда файл в 'tmpFileUrl' может быть использован как вам угодно.
Ответ 2
Вот мои настройки для высокого качества и небольшого размера файла (в балансе):
NSDictionary *recordSettings = @{AVEncoderAudioQualityKey: @(AVAudioQualityMedium),
AVFormatIDKey: @(kAudioFormatMPEG4AAC),
AVEncoderBitRateKey: @(128000),
AVNumberOfChannelsKey: @(1),
AVSampleRateKey: @(44100)};
Это дает вам близкий к треку качества AAC cd quality. Вы должны добавить файл с .m4a для чтения везде. Все остальные параметры устанавливаются в значения по умолчанию для устройств, что и должно быть в большинстве случаев.
Ответ 3
NSMutableDictionary *settings = [[NSMutableDictionary alloc] initWithCapacity:0];
[settings setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[settings setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
[settings setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[settings setValue :[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
[settings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[settings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
//Encoder
[settings setValue :[NSNumber numberWithInt:12000] forKey:AVEncoderBitRateKey];
[settings setValue :[NSNumber numberWithInt:8] forKey:AVEncoderBitDepthHintKey];
[settings setValue :[NSNumber numberWithInt:8] forKey:AVEncoderBitRatePerChannelKey];
[settings setValue :AVAudioQualityMin forKey:AVEncoderAudioQualityKey];