IOS录制音频 我用的是AVAudioRecorder这个控件,默认录制为caf格式文件,可用第三方lame转成mp3格式文件
使用前先引用框架 <AVFoundation/AVFoundation.h
>
1.录音用的控件是AVAudioRecorder,录音的主要代码:
recordedFile=[NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@", @"aaa",@"caf"]]];//录音文件的位置
recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:recordSetting error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
2.录音完成后,引用了lame之后,转化的过程核心代码:
NSString *cafFilePath =[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",@"aaa",@"caf"]] ;//原caf文件位置
NSString *mp3FilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",@"bbb",@"mp3"]];//转化过后的MP3文件位置
@try {
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
if(pcm == NULL)
{
NSLog(@"file not found");
}
else
{
fseek(pcm, 4*1024, SEEK_CUR); //skip file header,跳过头文件 有的文件录制会有音爆,加上此句话去音爆
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, 44100);//11025.0
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
return YES;
}
return NO;
}
@catch (NSException *exception) {
NSLog(@"%@",[exception description]);
return NO;
}
@finally {
NSData *data= [NSData dataWithContentsOfFile:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@", @"bbb",@"mp3"]]];//此处可以打断点看下data文件的大小,如果太小,很可能是个空文件
NSLog(@"执行完成");
}
3.播放控件用的是AVAudioPlayer,主要的代码:
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @”%@.%@”, @”bbb”,@”mp3”]]] error:&playerError];