我已经使用以下代码初始化了一个带有NSData的AVAudioPlayer对象,而NSData又包含了我主数据库中mp3的数据。
NSError *error;
NSString *filePathForBgAudio = [[NSBundle mainBundle] pathForResource:@"beebuzz10" ofType:@"mp3"];
NSData *bgAudioData = [NSData dataWithContentsOfFile:filePathForBgAudio];
bgAudioPlayer = [[AVAudioPlayer alloc] initWithData:bgAudioData error:&error];
bgAudioPlayer.delegate = self;
我在bgAudioPlayer
文件中声明了.h
。但是当我通过设置断点进行检查时,我发现在此行bgAudioPlayer = [[AVAudioPlayer alloc] initWithData:bgAudioData error:&error];
之后,bgAudioPlayer
仍然显示为nil
。但是filePathForBgAudio
和bgAudioData
已正确初始化并且包含数据。只有bgAudioPlayer
是nil
。上面的代码有什么问题?如何纠正这个?
答案 0 :(得分:1)
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"bubble"
ofType:@"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else
{
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
}
- (IBAction)playsound:(id)sender
{
[_audioPlayer play];
}
答案 1 :(得分:0)
NSError *error;
NSURL *filePathForBgAudio1 =[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"beebuzz10" ofType:@"mp3"]];
//NSString *filePathForBgAudio = [[NSBundle mainBundle] pathForResource:@"beebuzz10" ofType:@"mp3"];
// NSData *bgAudioData = [NSData dataWithContentsOfFile:filePathForBgAudio1];
bgAudioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:filePathForBgAudio1 error:&error];