我正在播放在后台模式中触发的音乐 - 但它会在一秒后停止,为什么?

时间:2012-01-03 22:51:53

标签: iphone objective-c audio avaudioplayer

我正在播放在背景中触发的声音但听起来不到一秒钟。 我试过wav和m4a文件。但我疯狂地找到问题的答案。 它甚至没有完成一个循环..你知道它为什么会发生吗?有人可以帮帮我吗?

这是播放代码:

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:[userProp valueForKey:@"romba"] ofType:@"m4a"];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:audioFilePath] error:NULL]; 
audioPlayer.delegate=self;
audioPlayer.numberOfLoops = -1;
[audioPlayer play];   

我试图调用此委托函数来检查问题,但没有什么我是我的控制台

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"finish playing");
}

-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"stops - decoder error");
    NSLog(@"error: %@",[error description]);
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player{
    NSLog(@"stops - decoder error");
} 

这是我添加AVAudoioPlayer的方式 -

-(void)syncAlarmProperties{
    NSUserDefaults *userProp = [NSUserDefaults standardUserDefaults];

    NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:[userProp valueForKey:@"alertProp"] ofType:@"wav"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:audioFilePath] error:NULL]; 

    audioPlayer.delegate=self;
    audioPlayer.numberOfLoops=-1;

} 

这是播放功能:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
{
[audioPlayer play];
}

1 个答案:

答案 0 :(得分:0)

如果您正在使用自动引用计数,则可能会在audioPlayer消息之后立即向-release发送-play消息。

在这种情况下,解决方案是在您的班级中添加AVAudioPlayer @property的实例,以确保播放器不会从您身下释放出来。