我有一个 ViewController :GLKViewController 使用此代码:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"background-music-aac" ofType:@"caf"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithData:data error:nil];
audio.delegate = self;
audio.volume = 1.0;
audio.numberOfLoops = -1;
[audio prepareToPlay];
[audio play];
[self setupContext];
[self setupDisplay];
}
但是...我的图形工作正常,但 iOS 模拟器不播放音乐。 我做错了什么吗?
最佳答案
假设您正在使用 ARC,一旦您的方法返回到其调用者,播放器就会被释放。引用this answer :
ARC inserts a release call to the audio player, so it's deallocated right after leaving the method where it is created.
尝试将 AVAudioPlayer
实现为属性。
如果您的data
为零,则该文件未正确添加到项目中。要将文件添加到项目中,只需将其拖放到目标中即可。
此外,AVAudioPlayer
有一个方法 initWithContentsOfURL:
,您可能需要使用该方法。
关于ios - Xcode AVAudioPlayer 未播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15586952/