iPhone不会播放音频文件
问题描述:
我想制作一个录音应用程序,所以显然我需要能够录制和播放音频文件。它看起来像在工作,根本没有错误,但它不会工作。我不确定它实际上是在录音吗?iPhone不会播放音频文件
它应该创建声音文件本身,对不对?我不需要在项目中输入完善的文件吗?
- (void)viewDidLoad
{
[super viewDidLoad];
playButton.enabled = NO;
stopButton.enabled = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[audioRecorder prepareToRecord];
}
}
// Methods called by the start recording button, stop recording, and play.
-(void) recordAudio
{
if (!audioRecorder.recording)
{
playButton.enabled = NO;
stopButton.enabled = YES;
[audioRecorder record];
}
}
-(void)stop
{
stopButton.enabled = NO;
playButton.enabled = YES;
recordButton.enabled = YES;
if (audioRecorder.recording)
{
[audioRecorder stop];
} else if (audioPlayer.playing) {
[audioPlayer stop];
}
}
-(void) playAudio
{
if (!audioRecorder.recording)
{
stopButton.enabled = YES;
recordButton.enabled = NO;
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:audioRecorder.url
error:&error];
audioPlayer.delegate = self;
if (error)
NSLog(@"Error: %@",
[error localizedDescription]);
else {
[audioPlayer setVolume:1.0];
[audioPlayer play];
}
}
}
// Delegate methods
-(void)audioPlayerDidFinishPlaying:
(AVAudioPlayer *)player successfully:(BOOL)flag
{
recordButton.enabled = YES;
stopButton.enabled = NO;
NSLog(@"did play");
}
-(void)audioPlayerDecodeErrorDidOccur:
(AVAudioPlayer *)player
error:(NSError *)error
{
NSLog(@"Decode Error occurred");
}
-(void)audioRecorderDidFinishRecording:
(AVAudioRecorder *)recorder
successfully:(BOOL)flag
{
NSLog(@"did record");
}
-(void)audioRecorderEncodeErrorDidOccur:
(AVAudioRecorder *)recorder
error:(NSError *)error
{
NSLog(@"Encode Error occurred");
}
提前致谢。我对整个录音工作很陌生,并且处理音频文件和目录。
答
尝试增加AVAudioSession代码如下..
NSError *error;
AVAudioSession * audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
[audioSession setActive:YES error: &error];
您刚才复制并粘贴http://www.techotopia.com/index.php/Recording_Audio_on_an_iPhone_with_AVAudioRecorder_%28iOS_4%29 – 2012-03-01 12:35:48
是我没有 - 当学习新的概念,我倾向于复制粘贴一些预定义的东西,让它工作,搅拌它并看看会发生什么,然后从头开始创建我自己 - 每个人都学习不同的东西,这对我很有用 - 所以我得首先得到这个工作:) – Seerex 2012-03-01 13:02:47
我只是问,那个问题是如果它从一开始就不工作,你不知道什么是它的工作。 – 2012-03-01 13:30:22