AVAudioPlayer refuses to play anything, but no error, etc

孤街醉人 提交于 2019-12-13 08:18:51

问题


This is the simplest possible AVAudioPlayer code, and it's just failing to play anything back. No errors, nothing in the console at all, the file is definitely being found as if I change the URL string to something which isn't there, I do get a crash. What am I doing wrong here? I've tried it with and without the delegate, as well as with and without prepareToPlay, and I can't get anything out. I've tried various sound files, too. Really tearing my hair out on this one!

@implementation ViewController

- (IBAction)playSound:(id)sender
{
    NSURL *soundLocation = [[NSURL alloc] initWithString:@"Lot01.wav"];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundLocation error:nil];
    [audioPlayer setDelegate:self];
    [audioPlayer play];
}

@end

回答1:


Turned out it was an issue with ARC releasing, I fixed it by adding a @property and @synthesize pair for the AVAudioPlayer in question, and declaring it as strong. It got rid of all of these errors, and played the file with no problems.




回答2:


It seems like it's not correctly getting the path to your file, maybe try something like this.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Lot01" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:filePath];

then init the AVAudioPlayer exactly how you were except in that case it'd be withContentsOfURL:url.



来源:https://stackoverflow.com/questions/9362448/avaudioplayer-refuses-to-play-anything-but-no-error-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!