这是我的方法:
-(void) playOrRecord:(UIButton *)sender {
if (playBool == YES) {
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
[player setNumberOfLoops:0];
[player play];
}
else if (playBool == NO) {
if ([recorder isRecording]) {
[recorder stop];
[nowRecording setImage:[UIImage imageNamed:@"NormalNormal.png"] forState:UIControlStateNormal];
[nowRecording setImage:[UIImage imageNamed:@"NormalSelected.png"] forState:UIControlStateSelected];
}
if (nowRecording == sender) {
nowRecording = nil;
return;
}
nowRecording = sender;
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
[sender setImage:[UIImage imageNamed:@"RecordingNormal.png"] forState:UIControlStateNormal];
[sender setImage:[UIImage imageNamed:@"RecordingSelected.png"] forState:UIControlStateSelected];
recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSettings error:&error];
[recorder record];
}
}
大多数都是自我解释的; playBool是一个BOOL,当它处于播放模式时为YES。 一切都在模拟器中工作,但是当我在设备上运行时,[记录器记录]返回NO。有没有人知道为什么会发生这种情况?
答案 0 :(得分:17)
如果您的代码中有任何位置,则可以进行此设置:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
将其更改为:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
设置错误的AVAudioSession类别将导致录制/播放失败。
答案 1 :(得分:4)
这是因为您无法修改设备上的应用程序包(已签名)。您可以录制到应用程序的docs文件夹或tmp目录。
答案 2 :(得分:3)
好的,解决了我自己的问题;我不知道为什么,但我必须在设备上录制到NSTemporaryDirectory。改变它完全修复它。
答案 3 :(得分:1)
我遇到了完全相同的问题。事实证明我遇到了错误生成的路径语句。 AVAudioRecorder初始化很好 - 没有事故 - 但iOS根本不允许我写它。为什么?看看:
/* The following code will fail - why? It fails because it is trying to write some path that is NOT accessible by
this app.
NSString *recordedAudioPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0]
stringByAppendingString:@"recorded.caf"];
*/
// Correction:
NSString *recordedAudioPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0];
recordedAudioPath = [recordedAudioPath stringByAppendingPathComponent:@"recorded.caf"];
NSURL *recordURL = [NSURL fileURLWithPath:recordedAudioPath];
现在这完全合情合理。谢谢你指导我正确的方向。
答案 4 :(得分:1)
此外,请确保您的应用可以访问麦克风(例如,在iOS设置中,向下滚动并找到您的应用,它应该有'麦克风',您需要切换到'开启')