我正在使用AV音频框架在iPhone上录制音频文件。这是当前的代码:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
现在我有另一个功能,我想将sound.caf文件发送到该功能,如:
NSData *soundData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:soundFilePath ofType:@"caf"]];
但出于某种原因,上面的行似乎返回了一个0kb的文件。
有什么建议吗?
答案 0 :(得分:1)
在您的代码中,文件网址不是全局的。你试试给出的代码
首先,您必须开始一个新的音频会话:
-(void) initAudioSession {
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
[audioSession setActive:YES error: &error];
}
-(void) recordStart {
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
tempFilePath = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@",audioFileName, @"caf"]]];
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@",audioFileName, @"caf"]]];
recorder = [[ AVAudioRecorder alloc] initWithURL:tempFilePath settings:recordSetting error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}
-(void) stopRecording{
[recorder stop];
}
-(void) playRecord{
avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:tempFilePath error:&error];
[avPlayer prepareToPlay];
[avPlayer play];
}
答案 1 :(得分:0)
也不要将文件打开为相同的文件名。
最后,您无法保存在应用目录中。您只能将数据保存在Documents文件夹中。