2014-03-06 131 views
1

第一次使用音频。可能是我缺少的东西,请指导AVAudioPlayer在播放时崩溃

我已添加AVFoundation框架。添加了#import

并将其添加到viewDidLoad中。

NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString* audioPath = [docPath stringByAppendingPathComponent:@"001.mp3"]; 
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:audioPath]; 

if (!fileExists) { 
    NSLog(@"Audio File not exist!"); 
}else{ 

    NSError *error; 
    NSURL *url = [[NSURL alloc] initFileURLWithPath:audioPath]; 
    NSData *audioData = [NSData dataWithContentsOfURL:url]; 

    self.audioPlayer = [AVAudioPlayer alloc]; 

    // It crashes at this line 
    self.audioPlayer = [self.audioPlayer initWithData:audioData error:&error]; 

    NSLog(@"%@",self.audioPlayer); 



} 
+0

什么消息崩溃? – zoul

+0

只在打印输出(lldb) – Mani

回答

0

试试这个,这对我有效。还检查音频文件是否播放。

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/001.caf", [[NSBundle mainBundle] resourcePath]]]; 

    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = -1; 

    if (audioPlayer == nil) 
     NSLog([error description]);    
    else 
     [audioPlayer play]; 
+0

打印这我试过你的解决方案,但仍然崩溃时,它在线试图发挥。 – Mani

+0

是的,它在另一个文件从我从哪里得到代码的想法工作。 – Mani

+0

是的,我检查示例项目中的相同文件。 – Mani

0

请确保您必须为AVAudioPlayer实例创建强属性。要么使其成为全球性的,要么建立强大的财产。

//Global iVAR 

AVAudioPlayer *avPlayer; 

OR

//Property 

@property(strong, nonatomic) AVAudioPlayer *avPlayer; 

,那么你应该能够播放音频。

+0

无法确认AVAudioPlayer的授权无法播放。 –

4

我对任何异常都使用通用断点。由于这个突破点没有任何细节,球员正在崩溃。刚刚删除该断点,现在工作正常。谢谢大家。