我一直面临录制音频并在 IOS 上播放的问题。
这是我用于录制的内容:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
recordSettings = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 16000.0],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatLinearPCM], AVFormatIDKey,// kAudioFormatLinearPCM
[NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
[NSNumber numberWithInt: AVAudioQualityLow],AVEncoderAudioQualityKey,
nil];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@", filePath, fileName] retain];
NSLog(@"recorderFilePath: %@",recorderFilePath);
NSURL *audioFileURL = [NSURL fileURLWithPath:recorderFilePath];
recorder = [[ AVAudioRecorder alloc] initWithURL:audioFileURL settings:recordSettings error:&err];
if(!recorder){
NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning"
message: [err localizedDescription]
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
//prepare to record
[recorder setDelegate: self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
并且在具有上述设置的 .wav 文件中录制对我来说效果很好。现在,问题在于回放。
下面是播放录制的 .wav 音频文件。
NSURL * url = [NSURL fileURLWithPath:filePath];
audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:url
error:&err] autorelease];
if (! audioPlayer) {
NSLog(@"Sound named '%@' had error %@", name, [err localizedDescription]);
} else {
[audioPlayer prepareToPlay]; // Getting the return value NO here.
}
// audioPlayer.volume = 1; // Tried setting different values, but of no help.
[audioPlayer play]; // Getting the return value NO here.
它没有抛出任何错误,但它什么也不做。没有声音正在播放。虽然可以使用播放器播放“.mp3”文件(资源中的测试文件),但播放使用上述设置录制的文件是个问题。
我不确定我在这里缺少什么。请帮忙!谢谢