修复录音文件长度为0的问题

This commit is contained in:
joywayer
2025-06-14 22:55:43 +08:00
parent 715e08f787
commit bba3ed1cb4
3 changed files with 343 additions and 207 deletions

View File

@@ -1614,7 +1614,7 @@
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a"; PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ylgamehall; "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = jxgamehall_dev;
TARGETED_DEVICE_FAMILY = 1; TARGETED_DEVICE_FAMILY = 1;
}; };
name = Debug; name = Debug;
@@ -1667,7 +1667,7 @@
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a"; PROVISIONING_PROFILE = "a8315ce6-c429-4b17-afb5-dbd05b31821a";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ylgamehall; "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = jxgamehall_dev;
TARGETED_DEVICE_FAMILY = 1; TARGETED_DEVICE_FAMILY = 1;
}; };
name = Release; name = Release;

View File

@@ -2014,7 +2014,7 @@
// //
// if(agentlist!=nil){ // if(agentlist!=nil){
// for (int j=0; j<[agentlist count]; j++) { // 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([FuncPublic isBlankString:[infotwo objectForKey:@"agentid"]]==NO){
// //
// if([[infotwo objectForKey:@"agentid"] isEqualToString:self.agentinfo]){ // if([[infotwo objectForKey:@"agentid"] isEqualToString:self.agentinfo]){
@@ -2022,32 +2022,32 @@
// if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) { // if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) {
// self.showmessage=[infotwo objectForKey:@"showmessage"]; // self.showmessage=[infotwo objectForKey:@"showmessage"];
// } // }
// //
// //
// //
// game_version=[infotwo objectForKey:@"game_version"]; // game_version=[infotwo objectForKey:@"game_version"];
// game_zip=[infotwo objectForKey:@"game_zip"]; // game_zip=[infotwo objectForKey:@"game_zip"];
// //
// if ([FuncPublic isBlankString:game_zip]==NO) { // if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip; // versonfig.game_download=game_zip;
// //
// } // }
// if ([game_version integerValue]!=0) { // if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version; // versonfig.game_version=game_version;
// //
// } // }
// //
// //
// NSArray *channellist=[infotwo objectForKey:@"channellist"]; // NSArray *channellist=[infotwo objectForKey:@"channellist"];
// if(channellist!=nil){ // if(channellist!=nil){
// for (int x=0; x<[channellist count]; x++) { // for (int x=0; x<[channellist count]; x++) {
// NSDictionary *infothree=[channellist objectAtIndex:x]; // NSDictionary *infothree=[channellist objectAtIndex:x];
// //
// if([FuncPublic isBlankString:[infothree objectForKey:@"channelid"]]==NO){ // if([FuncPublic isBlankString:[infothree objectForKey:@"channelid"]]==NO){
// if([[infothree objectForKey:@"channelid"] isEqualToString: self.channel_id]) // if([[infothree objectForKey:@"channelid"] isEqualToString: self.channel_id])
// { // {
// //
// //
// if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) { // if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) {
// self.showmessage=[infothree objectForKey:@"showmessage"]; // self.showmessage=[infothree objectForKey:@"showmessage"];
// } // }
@@ -2055,52 +2055,52 @@
// game_zip=[infothree objectForKey:@"game_zip"]; // game_zip=[infothree objectForKey:@"game_zip"];
// if ([FuncPublic isBlankString:game_zip]==NO) { // if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip; // versonfig.game_download=game_zip;
// //
// } // }
// if ([game_version integerValue]!=0) { // if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version; // versonfig.game_version=game_version;
// //
// } // }
// //
// //
// //
// //
// NSArray *marketlist=[infothree objectForKey:@"marketlist"]; // NSArray *marketlist=[infothree objectForKey:@"marketlist"];
// if(marketlist!=nil){ // if(marketlist!=nil){
// for (int i=0; i<[marketlist count]; i++) { // for (int i=0; i<[marketlist count]; i++) {
// NSDictionary *info=[marketlist objectAtIndex:i]; // NSDictionary *info=[marketlist objectAtIndex:i];
// if([FuncPublic isBlankString:[info objectForKey:@"marketid"]]==NO){ // if([FuncPublic isBlankString:[info objectForKey:@"marketid"]]==NO){
// if([[info objectForKey:@"marketid"] isEqualToString:self.market]){ // if([[info objectForKey:@"marketid"] isEqualToString:self.market]){
// //
// if (![self isEmptyString:[info objectForKey:@"showmessage"]]) { // if (![self isEmptyString:[info objectForKey:@"showmessage"]]) {
// self.showmessage=[info objectForKey:@"showmessage"]; // self.showmessage=[info objectForKey:@"showmessage"];
// } // }
// //
// //
// game_version=[info objectForKey:@"game_version"]; // game_version=[info objectForKey:@"game_version"];
// game_zip=[info objectForKey:@"game_zip"]; // game_zip=[info objectForKey:@"game_zip"];
// if ([FuncPublic isBlankString:game_zip]==NO) { // if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip; // versonfig.game_download=game_zip;
// //
// } // }
// if ([game_version integerValue]!=0) { // if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version; // versonfig.game_version=game_version;
// //
// } // }
// //
// //
// //
// } // }
// } // }
// //
// } // }
// } // }
// //
// //
// } // }
// } // }
// //
// //
// } // }
//// } //// }
//// ////
@@ -2109,8 +2109,8 @@
//// ////
//// } //// }
//// } //// }
// //
// //
// } // }
}else{ }else{
@@ -2168,22 +2168,65 @@
- (void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString*)_fileName{ - (void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString*)_fileName{
NSLog(@"录音完成,文件路径:%@ %@",_filePath,_fileName); NSLog(@"录音完成,文件路径:%@ %@",_filePath,_fileName);
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:_filePath] error:nil];
NSTimeInterval interval= play.duration; //
NSInteger time = round(interval); if (![[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
//4. NSLog(@"录音文件不存在: %@", _filePath);
if (play == nil) return;
{
NSLog(@"ERror creating player: %@", [play description]);
}else{
} }
NSString *amrPath = [FuncPublic GetPathByFileName: _fileName ofType:@"amr"];
if ([VoiceConverter ConvertWavToAmr:_filePath amrSavePath:amrPath]){ // 使fileURLWithPathURLWithString
NSData *test=[NSData dataWithContentsOfFile:amrPath]; NSError *error = nil;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; AVAudioPlayer *play = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_filePath] error:&error];
//text/html
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", 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);
}
// WAVAMR
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", @"text/html",
@"image/jpeg", @"image/jpeg",
@"image/png", @"image/png",
@@ -2191,27 +2234,44 @@
@"text/json", @"text/json",
@"audio/amr", @"audio/amr",
nil]; nil];
NSString *string=@"http://gameapi.0791ts.cn/api/UpLoad/PostFile"; NSString *string=@"http://gameapi.0791ts.cn/api/UpLoad/PostFile";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss"; formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@%08X.amr", str, arc4random()]; NSString *fileName = [NSString stringWithFormat:@"%@%08X.amr", str, arc4random()];
[manager POST:string parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { // ...
// NSData *imageData =UIImageJPEGRepresentation([UIImage imageNamed:@"sharelogo.jpg"],1); } else {
//() NSLog(@"AMR文件无效或为空");
[formData appendPartWithFileData:test name:@"file" fileName:fileName mimeType:@"audio/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]; UInt16 numChannels;
[_bridge callHandler:@"getaudiourl" data:@{ @"audiourl":audiourl,@"time":[NSString stringWithFormat:@"%ld",(long)time]} ]; [wavData getBytes:&numChannels range:NSMakeRange(22, 2)];
NSLog(@"上传成功");
} failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) { UInt32 sampleRate;
NSLog(@"上传失败"); [wavData getBytes:&sampleRate range:NSMakeRange(24, 4)];
}];
}else UInt16 bitsPerSample;
NSLog(@"wav转amr失败"); [wavData getBytes:&bitsPerSample range:NSMakeRange(34, 2)];
NSLog(@"WAV文件头信息 - RIFF标记: %@, WAVE标记: %@, 格式: %d, 通道数: %d, 采样率: %d, 采样位数: %d",
riffMarker, waveMarker, audioFormat, numChannels, sampleRate, bitsPerSample);
}
}
} }
#pragma mark - #pragma mark -
@@ -2287,134 +2347,132 @@
nickname = [nickname stringByReplacingOccurrencesOfString:@"'" withString:@""]; 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"] } ]; [_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];
}
}
} }
#pragma mark -
} - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
/*
*/
- (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)
{ {
if (error) if (motion == UIEventSubtypeMotionShake)
{ {
NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription); if(canshake)
//error
if (error.code == AMapLocationErrorLocateFailed)
{ {
return; [_bridge callHandler:@"shakeEnd" data:nil];
} if(canvoice)
}
//
if (location)
{
if (regeocode)
{
NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]);
if(regeocode.formattedAddress!=nil)
{ {
@try{ NSURL *url_=[[NSBundle mainBundle]URLForResource:@"shake_sound_male" withExtension:@"mp3"];
[_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} ]; AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil];
} @catch (NSException * e) { [audioPlayer prepareToPlay];
NSLog(@"Exception: %@", e); [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

View File

@@ -69,8 +69,6 @@
} }
return bCanRecord; return bCanRecord;
} }
//-(int)ifauth //-(int)ifauth
@@ -102,32 +100,86 @@
#pragma mark - #pragma mark -
- (void)beginRecordByFileName:(NSString*)_fileName;{ - (void)beginRecordByFileName:(NSString*)_fileName;{
NSLog(@"开始初始化录音,文件名: %@", _fileName);
// //
self.recordFileName = _fileName; self.recordFileName = _fileName;
self.recordFilePath = [VoiceRecorderBaseVC getPathByFileName:recordFileName ofType:@"wav"]; 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]);
}
// 使fileURLWithPathURL
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] self.recorder = [[[AVAudioRecorder alloc] initWithURL:fileURL
settings:[VoiceRecorderBaseVC getAudioRecorderSettingDict] settings:recordSettings
error:nil]autorelease]; error:&recError] autorelease];
if (recError) {
NSLog(@"录音初始化失败: %@", [recError localizedDescription]);
return;
}
recorder.delegate = self; recorder.delegate = self;
recorder.meteringEnabled = YES; recorder.meteringEnabled = YES;
[recorder prepareToRecord]; //
BOOL prepareSuccess = [recorder prepareToRecord];
if (!prepareSuccess) {
NSLog(@"录音准备失败");
return;
}
// //
curCount = 0; curCount = 0;
// //
canNotSend = NO; canNotSend = NO;
// //
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error:nil]; BOOL recordSuccess = [recorder record];
[[AVAudioSession sharedInstance] setActive:YES error:nil]; if (!recordSuccess) {
NSLog(@"开始录音失败");
return;
[recorder record]; }
NSLog(@"开始录音成功, 录音状态: %d", recorder.isRecording);
// //
[self startTimer]; [self startTimer];
@@ -167,12 +219,16 @@
} }
#pragma mark - #pragma mark -
- (void)updateMeters{ - (void)updateMeters{
if (recorder.isRecording){ if (recorder && recorder.isRecording){
// //
[recorder updateMeters]; [recorder updateMeters];
[recorderView updateMetersByAvgPower:[recorder averagePowerForChannel:0]]; float avgPower = [recorder averagePowerForChannel:0];
// NSLog(@"峰值:%f",[recorder averagePowerForChannel:0]); [recorderView updateMetersByAvgPower:avgPower];
//
if (fmod(curCount, 1.0) < 0.1) {
NSLog(@"录音中... 时长: %.1f秒, 峰值: %.2f", curCount, avgPower);
}
// //
if (curCount >= maxRecordTime - 10 && curCount < maxRecordTime) { if (curCount >= maxRecordTime - 10 && curCount < maxRecordTime) {
@@ -246,14 +302,25 @@
// //
[self stopTimer]; [self stopTimer];
NSLog(@"触摸结束,录音结束,当前录音时长: %.1f秒", curCount);
curTouchPoint = CGPointZero; curTouchPoint = CGPointZero;
[self removeScreenTouchObserver]; [self removeScreenTouchObserver];
[UIView hideViewByCompletion:^(BOOL finish){ [UIView hideViewByCompletion:^(BOOL finish){
// //
if (recorder.isRecording) if (recorder && recorder.isRecording) {
NSLog(@"停止录音");
[recorder stop]; [recorder stop];
//
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:recordFilePath]) {
NSDictionary *attrs = [fileManager attributesOfItemAtPath:recordFilePath error:nil];
NSLog(@"最终录音文件大小: %@ 字节", [attrs objectForKey:NSFileSize]);
}
}
if (canNotSend) { if (canNotSend) {
// //
@@ -269,11 +336,22 @@
#pragma mark - AVAudioRecorder Delegate Methods #pragma mark - AVAudioRecorder Delegate Methods
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{ - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
NSLog(@"录音停止"); NSLog(@"录音完成回调,成功: %d", flag);
if (!flag) {
NSLog(@"录音完成但不成功!");
}
[self stopTimer]; [self stopTimer];
curCount = 0; curCount = 0;
} }
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
NSLog(@"录音编码错误: %@", [error localizedDescription]);
[self stopTimer];
curCount = 0;
}
- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{ - (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{
NSLog(@"录音开始"); NSLog(@"录音开始");
[self stopTimer]; [self stopTimer];