iOS 使用EZAudio库生成wav出错的情况
使用EZAudio库
录M4A格式可以参考该库例子中的代码.
录wav格式得改下源码.看下面的代码
1 AVAudioSession *session = [AVAudioSession sharedInstance]; 2 NSError *error = nil; 3 [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]; 4 if (error) NSLog(@"audio session category error: %@", error); 5 [session setActive:YES error:&error]; 6 if (error) NSLog(@"audio session active error: %@", error); 7 8 self.microphone = [EZMicrophone microphoneWithDelegate:self]; 9 self.recorder = [EZRecorder recorderWithURL:[NSURL fileURLWithPath:RECORD_PATH] 10 clientFormat:[self.microphone audioStreamBasicDescription] 11 fileType:EZRecorderFileTypeWAV // 指定为WAV格式 12 delegate:self]; 13 14 [self.microphone startFetchingAudio]; 15 self.recording = YES; 16 self.audioTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f 17 target:self 18 selector:@selector(audioTimer:) 19 userInfo:nil repeats:YES]; 20 21 22 // 定时器计算录音时间 23 - (void)audioTimer:(NSTimer *)timer 24 { 25 self.audioV.audioTime = (int)self.recorder.currentTime; 26 } 27 28 // 这是个代理函数 可以用来计算音量 29 - (void)microphone:(EZMicrophone *)microphone 30 hasAudioReceived:(float **)buffer 31 withBufferSize:(UInt32)bufferSize 32 withNumberOfChannels:(UInt32)numberOfChannels 33 { 34 dispatch_async(dispatch_get_main_queue(), ^{ 35 if (self.isRecording) { 36 CGFloat vol = [EZAudioUtilities RMS:buffer[0] length:bufferSize]; 37 //vol就是音量 *150是因为放大后控制控件宽度 38 self.audioV.vol = (int)(vol * 150); 39 } 40 }); 41 }
以上这种写法会闪退.原因是这个库录wav格式配置不对.
修改库中EZAudioUtilities.m
文件第287行函数为
1 + (AudioStreamBasicDescription)stereoFloatInterleavedFormatWithSampleRate:(float)sampleRate 2 { 3 #if 0 // 这个库本身的代码 录wav格式直接出错 闪退 4 AudioStreamBasicDescription asbd; 5 UInt32 floatByteSize = sizeof(float); 6 asbd.mChannelsPerFrame = 2; 7 asbd.mBitsPerChannel = 8 * floatByteSize; 8 asbd.mBytesPerFrame = asbd.mChannelsPerFrame * floatByteSize; 9 asbd.mFramesPerPacket = 1; 10 asbd.mBytesPerPacket = asbd.mFramesPerPacket * asbd.mBytesPerFrame; 11 asbd.mFormatFlags = kAudioFormatFlagIsFloat; 12 asbd.mFormatID = kAudioFormatLinearPCM; 13 asbd.mSampleRate = sampleRate; 14 asbd.mReserved = 0; 15 return asbd; 16 #endif 17 18 // 改用这种配置录出来就是wav格式 19 AudioStreamBasicDescription asbd; 20 memset(&asbd, 0, sizeof(asbd)); 21 asbd.mSampleRate = 8000; //采样率 22 asbd.mFormatID = kAudioFormatLinearPCM; 23 asbd.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; 24 asbd.mChannelsPerFrame = 1; //单声道 25 asbd.mFramesPerPacket = 1; //每一个packet一侦数据 26 asbd.mBitsPerChannel = 16; //每个采样点16bit量化 27 asbd.mBytesPerFrame = (asbd.mBitsPerChannel / 8) * asbd.mChannelsPerFrame; 28 asbd.mBytesPerPacket = asbd.mBytesPerFrame ; 29 30 return asbd; 31 }
使用EncodeAudio库转为amr格式
提取密码: prdq
1 //转成amr格式后发送 2 NSData * data = [[NSData alloc] initWithContentsOfFile:RECORD_PATH]; 3 data = [EncodeAudio convertWavToAmrFile:data];