我正在尝试创建一个应用程序,允许某人在 iOS5 中永久录制和保存他们的声音。然后可以随时播放该录音。只要用户停留在记录和播放音频的视图上,我的代码就可以工作,但是当我离开视图时,回到它并尝试播放音频,我收到此错误:
错误:操作无法完成。(OSStatus 错误 -50。)
显然,离开视图会导致保存在 Documents 文件夹中的文件无法正常工作?有人对我如何解决这个问题有解决方案或答案吗?
我录制和播放音频的代码如下:
- (IBAction)playSound:(id)sender {
if (!self.audioRecorder.recording)
{
NSError *error;
if (self.audioPlayer)
self.audioPlayer = nil;
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:self.audioRecorder.url
error:&error];
self.audioPlayer.delegate = self;
[self.audioPlayer prepareToPlay];
if (error)
NSLog(@"Error: %@",
[error localizedDescription]);
else
[self.audioPlayer play];
}
}
- (IBAction)recordSound:(id)sender {
if(!self.audioRecorder.recording)
{
self.dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
self.docsDir = [self.dirPaths objectAtIndex:0];
self.soundFilePath = [self.docsDir
stringByAppendingPathComponent:@"sound.caf"];
self.soundFileURL = [NSURL fileURLWithPath:self.soundFilePath];
self.recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
self.audioRecorder = [[AVAudioRecorder alloc]
initWithURL:self.soundFileURL
settings:self.recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[self.audioRecorder prepareToRecord];
}
[self.audioRecorder record];
[self.audioRecorder recordForDuration:(NSTimeInterval) 5];
[self.record setTitle:@"Stop" forState: UIControlStateNormal];
}
else if (self.audioRecorder.recording)
{
[self.audioRecorder stop];
[self.record setTitle:@"Record" forState: UIControlStateNormal];
}
else if (self.audioPlayer.playing) {
[self.audioPlayer stop];
}
}