在iPhone应用程序中以mp3格式录制音频

时间:2012-05-11 09:43:56

标签: iphone objective-c ios avaudioplayer avaudiorecorder

我正在开发一款以.wav格式录制音频的iPhone应用程序。

以下是代码:

NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc]init];         
[recordSetting setValue :[NSNumber  numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];         
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];




NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
 NSUserDomainMask, YES);

  NSString *documentsDirectory = [path objectAtIndex:0]; 

  NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:@"test.wav"];

 recordedTmpFile = [NSURL fileURLWithPath:myDBnew];

NSLog(@"Using File called: %@",recordedTmpFile);

        recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];
        [recorder setDelegate:self];
        [recorder prepareToRecord];
        [recorder record];

以上代码以.wav格式录制音频。如果我想使用密钥kAudioFormatMPEGLayer3(mp3)而不是kAudioFormatLinearPCM(.wav)在MP3中录制音频,我还需要做出哪些其他更改? recordSetting字典中的更改,如采样率,频道和所有。

或建议任何兼容iPhone和Android的音频格式,尺寸较小,可以直接从iPhone应用程序录制。

2 个答案:

答案 0 :(得分:24)

你不能用MP3录制,它在编码方面是一种专有格式。这些是我使用的设置,录制时间为2分钟,大约为150KB:

NSString *tempDir = NSTemporaryDirectory();
NSString *soundFilePath = [tempDir stringByAppendingPathComponent:@"sound.m4a"];

NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                  [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
                                  [NSNumber numberWithInt:16], AVEncoderBitRateKey,
                                  [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                  [NSNumber numberWithFloat:8000.0], AVSampleRateKey,
                                  [NSNumber numberWithInt:8], AVLinearPCMBitDepthKey,
                                  nil];

同样进行转换是处理器密集型操作,如果您将此音频发送到服务器,您可以使用FFMPEG与mp3lame库在服务器上进行音频转换。

编辑:这是Android录制的代码,它设置为AMR编码,因为AAC仅支持Honeycomb。

mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setAudioChannels(1);
mediaRecorder.setOutputFile("sample.m4a");

答案 1 :(得分:1)

您无法在.mp3文件中录制音频。 kAudioFormatMPEGLayer3仅适用于playback the .mp3 format audio。有no codec available for .mp3 recording。您需要以aacwav格式进行记录,并将其转换为.mp3格式。

更好地查看以下链接和图片:

Audio Recording Reference

enter image description here

这是一个学习转换音频格式基础的链接:

Audio Converter Reference