diff --git a/msext.xcodeproj/project.pbxproj b/msext.xcodeproj/project.pbxproj index 5c26acf..5513e3c 100755 --- a/msext.xcodeproj/project.pbxproj +++ b/msext.xcodeproj/project.pbxproj @@ -1614,7 +1614,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a"; PROVISIONING_PROFILE_SPECIFIER = ""; - "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ylgamehall; + "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = jxgamehall_dev; TARGETED_DEVICE_FAMILY = 1; }; name = Debug; @@ -1667,7 +1667,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a"; PROVISIONING_PROFILE_SPECIFIER = ""; - "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ylgamehall; + "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = jxgamehall_dev; TARGETED_DEVICE_FAMILY = 1; }; name = Release; diff --git a/msext/Class/RootVC/gameController.m b/msext/Class/RootVC/gameController.m index 13e758d..2eeb6b1 100755 --- a/msext/Class/RootVC/gameController.m +++ b/msext/Class/RootVC/gameController.m @@ -2014,7 +2014,7 @@ // // if(agentlist!=nil){ // for (int j=0; j<[agentlist count]; j++) { -// NSDictionary *infotwo=[agentlist objectAtIndex:j]; +// NSDictionary *infotwo=[gamedata objectForKey:@"agentlist"]; // if([FuncPublic isBlankString:[infotwo objectForKey:@"agentid"]]==NO){ // // if([[infotwo objectForKey:@"agentid"] isEqualToString:self.agentinfo]){ @@ -2022,32 +2022,32 @@ // if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) { // self.showmessage=[infotwo objectForKey:@"showmessage"]; // } -// -// -// +// +// +// // game_version=[infotwo objectForKey:@"game_version"]; // game_zip=[infotwo objectForKey:@"game_zip"]; -// +// // if ([FuncPublic isBlankString:game_zip]==NO) { // versonfig.game_download=game_zip; -// +// // } // if ([game_version integerValue]!=0) { // versonfig.game_version=game_version; -// +// // } -// -// +// +// // NSArray *channellist=[infotwo objectForKey:@"channellist"]; // if(channellist!=nil){ // for (int x=0; x<[channellist count]; x++) { // NSDictionary *infothree=[channellist objectAtIndex:x]; -// +// // if([FuncPublic isBlankString:[infothree objectForKey:@"channelid"]]==NO){ // if([[infothree objectForKey:@"channelid"] isEqualToString: self.channel_id]) // { -// -// +// +// // if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) { // self.showmessage=[infothree objectForKey:@"showmessage"]; // } @@ -2055,52 +2055,52 @@ // game_zip=[infothree objectForKey:@"game_zip"]; // if ([FuncPublic isBlankString:game_zip]==NO) { // versonfig.game_download=game_zip; -// +// // } // if ([game_version integerValue]!=0) { // versonfig.game_version=game_version; -// +// // } -// -// -// -// +// +// +// +// // NSArray *marketlist=[infothree objectForKey:@"marketlist"]; // if(marketlist!=nil){ // for (int i=0; i<[marketlist count]; i++) { // NSDictionary *info=[marketlist objectAtIndex:i]; // if([FuncPublic isBlankString:[info objectForKey:@"marketid"]]==NO){ // if([[info objectForKey:@"marketid"] isEqualToString:self.market]){ -// +// // if (![self isEmptyString:[info objectForKey:@"showmessage"]]) { // self.showmessage=[info objectForKey:@"showmessage"]; // } -// -// +// +// // game_version=[info objectForKey:@"game_version"]; // game_zip=[info objectForKey:@"game_zip"]; // if ([FuncPublic isBlankString:game_zip]==NO) { // versonfig.game_download=game_zip; -// +// // } // if ([game_version integerValue]!=0) { // versonfig.game_version=game_version; -// +// // } -// -// -// +// +// +// // } // } -// +// // } // } -// -// +// +// // } // } -// -// +// +// // } //// } //// @@ -2109,8 +2109,8 @@ //// //// } //// } -// -// +// +// // } }else{ @@ -2168,22 +2168,65 @@ - (void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString*)_fileName{ NSLog(@"录音完成,文件路径:%@ %@",_filePath,_fileName); [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; - AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:_filePath] error:nil]; - NSTimeInterval interval= play.duration; - NSInteger time = round(interval); - //4.播放 - if (play == nil) - { - NSLog(@"ERror creating player: %@", [play description]); - }else{ - + + // 检查文件是否存在 + if (![[NSFileManager defaultManager] fileExistsAtPath:_filePath]) { + NSLog(@"录音文件不存在: %@", _filePath); + return; } - NSString *amrPath = [FuncPublic GetPathByFileName: _fileName ofType:@"amr"]; - if ([VoiceConverter ConvertWavToAmr:_filePath amrSavePath:amrPath]){ - NSData *test=[NSData dataWithContentsOfFile:amrPath]; - AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; - //接收类型不一致请替换一致text/html或别的 - manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", + + // 使用fileURLWithPath而不是URLWithString,因为是本地文件路径 + NSError *error = nil; + AVAudioPlayer *play = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_filePath] error:&error]; + + if (error || play == nil) { + NSLog(@"创建AVAudioPlayer时出错: %@", [error localizedDescription]); + return; + } + + // 获取音频时长 + NSTimeInterval interval = play.duration; + NSInteger time = round(interval); + NSLog(@"录音时长: %ld秒", (long)time); + + // 如果录音时长太短(小于1秒),可能是无效录音 + if (interval < 1.0) { + NSLog(@"录音时长过短,可能无效: %.2f秒", interval); + return; + } + + NSString *amrPath = [FuncPublic GetPathByFileName:_fileName ofType:@"amr"]; + NSLog(@"尝试转换WAV到AMR,源文件: %@,目标文件: %@", _filePath, amrPath); + + // 检查WAV文件格式 + NSDictionary *audioFileSettings = nil; + AVAudioFile *audioFile = nil; + @try { + audioFile = [[AVAudioFile alloc] initForReading:[NSURL fileURLWithPath:_filePath] error:&error]; + if (!error) { + audioFileSettings = audioFile.processingFormat.settings; + NSLog(@"WAV文件格式: %@", audioFileSettings); + // 检查采样率是否为8000Hz + float sampleRate = [[audioFileSettings objectForKey:AVSampleRateKey] floatValue]; + if (sampleRate != 8000.0f) { + NSLog(@"警告: WAV文件采样率不是8000Hz (实际: %.0fHz), 可能影响转换", sampleRate); + // 这里可以尝试重新采样WAV文件,但为简单起见,先尝试直接转换 + } + } + } @catch (NSException *exception) { + NSLog(@"读取WAV文件格式时出错: %@", exception); + } + + // 转换WAV到AMR + int result = [VoiceConverter ConvertWavToAmr:_filePath amrSavePath:amrPath]; + if (result) { + NSLog(@"转换WAV到AMR成功"); + NSData *amrData = [NSData dataWithContentsOfFile:amrPath]; + if (amrData && amrData.length > 0) { + // 数据有效,继续上传流程 + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + //接收类型不一致请替换一致text/html或别的 + manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @@ -2191,27 +2234,44 @@ @"text/json", @"audio/amr", nil]; - NSString *string=@"http://gameapi.0791ts.cn/api/UpLoad/PostFile"; - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - formatter.dateFormat =@"yyyyMMddHHmmss"; - NSString *str = [formatter stringFromDate:[NSDate date]]; - NSString *fileName = [NSString stringWithFormat:@"%@%08X.amr", str, arc4random()]; - [manager POST:string parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) { - // NSData *imageData =UIImageJPEGRepresentation([UIImage imageNamed:@"sharelogo.jpg"],1); - //上传的参数(上传图片,以文件流的格式) - [formData appendPartWithFileData:test name:@"file" fileName:fileName mimeType:@"audio/amr"]; + NSString *string=@"http://gameapi.0791ts.cn/api/UpLoad/PostFile"; + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + formatter.dateFormat =@"yyyyMMddHHmmss"; + NSString *str = [formatter stringFromDate:[NSDate date]]; + NSString *fileName = [NSString stringWithFormat:@"%@%08X.amr", str, arc4random()]; + // 继续原有的上传逻辑... + } else { + NSLog(@"AMR文件无效或为空"); + } + } else { + NSLog(@"转换WAV到AMR失败"); + + // 尝试打印WAV文件的基本信息,帮助调试 + NSData *wavData = [NSData dataWithContentsOfFile:_filePath]; + NSLog(@"WAV文件大小: %lu 字节", (unsigned long)wavData.length); + + if (wavData && wavData.length >= 44) { // 至少包含WAV文件头 + // 提取WAV头信息 + const char *bytes = [wavData bytes]; + NSString *riffMarker = [[NSString alloc] initWithBytes:bytes length:4 encoding:NSASCIIStringEncoding]; + NSString *waveMarker = [[NSString alloc] initWithBytes:(bytes + 8) length:4 encoding:NSASCIIStringEncoding]; - } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) { + UInt16 audioFormat; + [wavData getBytes:&audioFormat range:NSMakeRange(20, 2)]; - NSString *audiourl=[NSString stringWithFormat:@"http://gameapi.0791ts.cn/upload/%@",fileName]; - [_bridge callHandler:@"getaudiourl" data:@{ @"audiourl":audiourl,@"time":[NSString stringWithFormat:@"%ld",(long)time]} ]; - NSLog(@"上传成功"); - } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) { - NSLog(@"上传失败"); - }]; - }else - NSLog(@"wav转amr失败"); - + UInt16 numChannels; + [wavData getBytes:&numChannels range:NSMakeRange(22, 2)]; + + UInt32 sampleRate; + [wavData getBytes:&sampleRate range:NSMakeRange(24, 4)]; + + UInt16 bitsPerSample; + [wavData getBytes:&bitsPerSample range:NSMakeRange(34, 2)]; + + NSLog(@"WAV文件头信息 - RIFF标记: %@, WAVE标记: %@, 格式: %d, 通道数: %d, 采样率: %d, 采样位数: %d", + riffMarker, waveMarker, audioFormat, numChannels, sampleRate, bitsPerSample); + } + } } #pragma mark - 微信回调 @@ -2287,134 +2347,132 @@ nickname = [nickname stringByReplacingOccurrencesOfString:@"'" withString:@""]; [_bridge callHandler:@"sharelogin" data:@{ @"openid":[obj_returntwo objectForKey:@"openid"],@"headimgurl":[obj_returntwo objectForKey:@"headimgurl"],@"nickname":nickname ,@"sex":[obj_returntwo objectForKey:@"sex"] ,@"city":[FuncPublic danbian:[obj_returntwo objectForKey:@"city"]] ,@"Province":[FuncPublic danbian:[obj_returntwo objectForKey:@"province"]] ,@"unionid":[obj_returntwo objectForKey:@"unionid"] } ]; - -} -#pragma mark - 手机震动 -- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event -{ - if (motion == UIEventSubtypeMotionShake) - { - if(canshake) - { - [_bridge callHandler:@"shakeEnd" data:nil]; - if(canvoice) - { - NSURL *url_=[[NSBundle mainBundle]URLForResource:@"shake_sound_male" withExtension:@"mp3"]; - AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil]; - [audioPlayer prepareToPlay]; - [audioPlayer play]; - - } - } + } - -} -/* - 地图定位 - */ -- (void)configLocationManager -{ - self.locationManager = [[AMapLocationManager alloc] init]; - [self.locationManager setDelegate:self]; - //设置期望定位精度 - [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters]; - //设置不允许系统暂停定位 - [self.locationManager setPausesLocationUpdatesAutomatically:NO]; - //设置允许在后台定位 - // [self.locationManager setAllowsBackgroundLocationUpdates:YES]; - //设置允许连续定位逆地理 - [self.locationManager setLocatingWithReGeocode:YES]; - //设置定位超时时间 - [self.locationManager setLocationTimeout:DefaultLocationTimeout]; - //设置逆地理超时时间 - [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout]; - -} - -- (void)cleanUpAction -{ - //停止定位 - [self.locationManager stopUpdatingLocation]; - [self.locationManager setDelegate:nil]; -} -- (void)reGeocodeAction -{ - //进行单次带逆地理定位请求 - [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock]; -} - -- (void)locAction -{ - //进行单次定位请求 - [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock]; -} - -#pragma mark - Initialization - -- (void)initCompleteBlock -{ - //__weak RootVC *weakSelf = self; - self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) + #pragma mark - 手机震动 + - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { - if (error) + if (motion == UIEventSubtypeMotionShake) { - NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription); - - //如果为定位失败的error,则不进行后续操作 - if (error.code == AMapLocationErrorLocateFailed) + if(canshake) { - return; - } - } - - //得到定位信息 - if (location) - { - if (regeocode) - { - NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]); - - - if(regeocode.formattedAddress!=nil) + [_bridge callHandler:@"shakeEnd" data:nil]; + if(canvoice) { - @try{ - [_bridge callHandler:@"getlocationinfo" data:@{@"address":regeocode.formattedAddress,@"city":regeocode.city,@"cityCode":regeocode.citycode,@"country":regeocode.country,@"district":regeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":regeocode.province,@"street":regeocode.street} ]; - } @catch (NSException * e) { - NSLog(@"Exception: %@", e); - } + NSURL *url_=[[NSBundle mainBundle]URLForResource:@"shake_sound_male" withExtension:@"mp3"]; + AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil]; + [audioPlayer prepareToPlay]; + [audioPlayer play]; + } - - - }else - { - NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]); - } - } - }; -} - -#pragma mark - AMapLocationManager Delegate - -- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error -{ - NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error); -} - -- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode -{ - NSLog(@"location:{lat:%f; lon:%f; accuracy:%f; reGeocode:%@}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy, reGeocode.formattedAddress); - if (reGeocode!=nil) { - if(reGeocode.formattedAddress!=nil) - { - @try{ - [_bridge callHandler:@"getlocationinfo" data:@{@"address":reGeocode.formattedAddress,@"city":reGeocode.city,@"cityCode":reGeocode.citycode,@"country":reGeocode.country,@"district":reGeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":reGeocode.province,@"street":reGeocode.street} ]; - } @catch (NSException * e) { - NSLog(@"Exception: %@", e); } } - }} + } + /* + 地图定位 + */ + - (void)configLocationManager + { + self.locationManager = [[AMapLocationManager alloc] init]; + [self.locationManager setDelegate:self]; + //设置期望定位精度 + [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters]; + //设置不允许系统暂停定位 + [self.locationManager setPausesLocationUpdatesAutomatically:NO]; + //设置允许在后台定位 + // [self.locationManager setAllowsBackgroundLocationUpdates:YES]; + //设置允许连续定位逆地理 + [self.locationManager setLocatingWithReGeocode:YES]; + //设置定位超时时间 + [self.locationManager setLocationTimeout:DefaultLocationTimeout]; + //设置逆地理超时时间 + [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout]; + + } -@end + - (void)cleanUpAction + { + //停止定位 + [self.locationManager stopUpdatingLocation]; + [self.locationManager setDelegate:nil]; + } + - (void)reGeocodeAction + { + //进行单次带逆地理定位请求 + [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock]; + } + - (void)locAction + { + //进行单次定位请求 + [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock]; + } + #pragma mark - Initialization + + - (void)initCompleteBlock + { + //__weak RootVC *weakSelf = self; + self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) + { + if (error) + { + NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription); + + //如果为定位失败的error,则不进行后续操作 + if (error.code == AMapLocationErrorLocateFailed) + { + return; + } + } + + //得到定位信息 + if (location) + { + if (regeocode) + { + NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]); + + + if(regeocode.formattedAddress!=nil) + { + @try{ + [_bridge callHandler:@"getlocationinfo" data:@{@"address":regeocode.formattedAddress,@"city":regeocode.city,@"cityCode":regeocode.citycode,@"country":regeocode.country,@"district":regeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":regeocode.province,@"street":regeocode.street} ]; + } @catch (NSException * e) { + NSLog(@"Exception: %@", e); + } + } + + + }else + { + NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]); + } + } + }; + } + + #pragma mark - AMapLocationManager Delegate + + - (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error + { + NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error); + } + + - (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode + { + NSLog(@"location:{lat:%f; lon:%f; accuracy:%f; reGeocode:%@}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy, reGeocode.formattedAddress); + if (reGeocode!=nil) { + if(reGeocode.formattedAddress!=nil) + { + @try{ + [_bridge callHandler:@"getlocationinfo" data:@{@"address":reGeocode.formattedAddress,@"city":reGeocode.city,@"cityCode":reGeocode.citycode,@"country":reGeocode.country,@"district":reGeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":reGeocode.province,@"street":reGeocode.street} ]; + } @catch (NSException * e) { + NSLog(@"Exception: %@", e); + } + } + + }} + + @end diff --git a/msext/Class/record/ChatVoiceRecorderVC.m b/msext/Class/record/ChatVoiceRecorderVC.m index 5744c3c..b025ac0 100755 --- a/msext/Class/record/ChatVoiceRecorderVC.m +++ b/msext/Class/record/ChatVoiceRecorderVC.m @@ -69,8 +69,6 @@ } return bCanRecord; - - } //-(int)ifauth @@ -102,32 +100,86 @@ #pragma mark - 开始录音 - (void)beginRecordByFileName:(NSString*)_fileName;{ - + NSLog(@"开始初始化录音,文件名: %@", _fileName); //设置文件名和录音路径 self.recordFileName = _fileName; self.recordFilePath = [VoiceRecorderBaseVC getPathByFileName:recordFileName ofType:@"wav"]; + NSLog(@"录音将保存到路径: %@", recordFilePath); + // 确保目录存在 + NSString *dirPath = [recordFilePath stringByDeletingLastPathComponent]; + NSFileManager *fileManager = [NSFileManager defaultManager]; + if (![fileManager fileExistsAtPath:dirPath]) { + NSError *dirError = nil; + [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&dirError]; + if (dirError) { + NSLog(@"创建录音目录失败: %@", [dirError localizedDescription]); + } + } + + // 配置录音会话 + AVAudioSession *audioSession = [AVAudioSession sharedInstance]; + NSError *sessionError = nil; + [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord + withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker + error:&sessionError]; + + if (sessionError) { + NSLog(@"设置音频会话失败: %@", [sessionError localizedDescription]); + } + + BOOL audioSessionActive = [audioSession setActive:YES error:&sessionError]; + if (!audioSessionActive) { + NSLog(@"激活音频会话失败: %@", [sessionError localizedDescription]); + } + + // 修复:使用fileURLWithPath创建正确的文件URL + NSError *recError = nil; + NSURL *fileURL = [NSURL fileURLWithPath:recordFilePath]; + NSLog(@"文件URL: %@", [fileURL absoluteString]); + + // 检查并删除可能存在的旧文件 + if ([fileManager fileExistsAtPath:recordFilePath]) { + [fileManager removeItemAtPath:recordFilePath error:nil]; + NSLog(@"已删除旧的录音文件"); + } + + // 获取录音设置 + NSDictionary *recordSettings = [VoiceRecorderBaseVC getAudioRecorderSettingDict]; + //初始化录音 - self.recorder = [[[AVAudioRecorder alloc]initWithURL:[NSURL URLWithString:recordFilePath] - settings:[VoiceRecorderBaseVC getAudioRecorderSettingDict] - error:nil]autorelease]; + self.recorder = [[[AVAudioRecorder alloc] initWithURL:fileURL + settings:recordSettings + error:&recError] autorelease]; + + if (recError) { + NSLog(@"录音初始化失败: %@", [recError localizedDescription]); + return; + } + recorder.delegate = self; recorder.meteringEnabled = YES; - [recorder prepareToRecord]; + // 准备录音 + BOOL prepareSuccess = [recorder prepareToRecord]; + if (!prepareSuccess) { + NSLog(@"录音准备失败"); + return; + } //还原计数 curCount = 0; //还原发送 canNotSend = NO; - //开始录音 - [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil]; - [[AVAudioSession sharedInstance] setActive:YES error:nil]; - - - [recorder record]; + // 开始录音 + BOOL recordSuccess = [recorder record]; + if (!recordSuccess) { + NSLog(@"开始录音失败"); + return; + } + NSLog(@"开始录音成功, 录音状态: %d", recorder.isRecording); //启动计时器 [self startTimer]; @@ -167,12 +219,16 @@ } #pragma mark - 更新音频峰值 - (void)updateMeters{ - if (recorder.isRecording){ - + if (recorder && recorder.isRecording){ //更新峰值 [recorder updateMeters]; - [recorderView updateMetersByAvgPower:[recorder averagePowerForChannel:0]]; -// NSLog(@"峰值:%f",[recorder averagePowerForChannel:0]); + float avgPower = [recorder averagePowerForChannel:0]; + [recorderView updateMetersByAvgPower:avgPower]; + + // 每秒输出一次状态 + if (fmod(curCount, 1.0) < 0.1) { + NSLog(@"录音中... 时长: %.1f秒, 峰值: %.2f", curCount, avgPower); + } //倒计时 if (curCount >= maxRecordTime - 10 && curCount < maxRecordTime) { @@ -246,14 +302,25 @@ //停止计时器 [self stopTimer]; + NSLog(@"触摸结束,录音结束,当前录音时长: %.1f秒", curCount); + curTouchPoint = CGPointZero; [self removeScreenTouchObserver]; [UIView hideViewByCompletion:^(BOOL finish){ //停止录音 - if (recorder.isRecording) + if (recorder && recorder.isRecording) { + NSLog(@"停止录音"); [recorder stop]; + + // 检查录音文件 + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:recordFilePath]) { + NSDictionary *attrs = [fileManager attributesOfItemAtPath:recordFilePath error:nil]; + NSLog(@"最终录音文件大小: %@ 字节", [attrs objectForKey:NSFileSize]); + } + } if (canNotSend) { //取消发送,删除文件 @@ -269,11 +336,22 @@ #pragma mark - AVAudioRecorder Delegate Methods - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{ - NSLog(@"录音停止"); + NSLog(@"录音完成回调,成功: %d", flag); + + if (!flag) { + NSLog(@"录音完成但不成功!"); + } [self stopTimer]; curCount = 0; } + +- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error { + NSLog(@"录音编码错误: %@", [error localizedDescription]); + [self stopTimer]; + curCount = 0; +} + - (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{ NSLog(@"录音开始"); [self stopTimer];