我正在尝试创建一个允许某人在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];
}
}
答案 0 :(得分:1)
我猜它发生了,因为当你录制文件时,你指定了一个文件名,并且url保存在self.audioRecorder.url
属性中。
离开视图后,AVAudioPlayer
对象self.audioPlayer
和self.audioRecorder
将从内存中释放。
当你回来时,尝试使用属性self.audioRecorder.url
初始化它并不存在,因此用nil初始化。
尝试从此处更改alloc和init:
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:self.audioRecorder.url
error:&error];
到此:
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.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:self.soundFileURL
error:&error];
或类似的东西,只要用存储在文件系统中的文件初始化播放器即可。不是来自存储在内存中的对象