我正在开发的程序需要我保存大量的 AVAudioRecorder 文件以备将来使用。然而,虽然我知道如何保存和录制静态数量的文件,但我希望能够动态保存它们,而不必在每次录制时都使用相同的声音文件 URL(如“sound.caf”) ,并且能够在我需要的时候播放这些文件。有人知道我会怎么做吗?
下面的代码显示了我当前的录制代码:
- (IBAction)playSound:(id)sender {
if (!self.audioRecorder.recording)
{
NSError *error;
if (self.audioPlayer)
self.audioPlayer = nil;
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];
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];
}
}