Reputation: 24190
I have a UIViewController subclass for a game with an AVAudioPlayer to play a song in the background. In my viewDidLoad method, I have the following code:
[super viewDidLoad];
...
[NSTimer scheduledTimerWithInterval: 0.03 target: self selector: @selector(gameLoop) userInfo: nil repeats: YES];
NSString *path = @"path-to-song";
self->audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath: path] error: NULL];
audioPlayer.delegate = self;
audioPlayer.numberOfLoops = - 1;
[audioPlayer play];
gameLoop is a method which contains the core logic for the game. When I run the app on my testing device, the audio plays, but it appears to be frozen, and gameLoop doesn't run normally. If I remove all the AVAudioPlayer code, the game works fine otherwise. It seems like there's some threading issue here that I'm not aware of. Any ideas?
Upvotes: 1
Views: 918
Reputation: 939
Try moving your AVAudioPlayer code into a method and running it in a background thread like so:
- (void)playSong:(NSURL*)atURL
{
self->audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: atURL error: NULL];
audioPlayer.delegate = self;
audioPlayer.numberOfLoops = - 1;
[audioPlayer play];
}
- (void)viewDidLoad
{
[super viewDidLoad];
...
NSURL* url = [NSURL fileURLWithPath: @"path-to-song"]
[self performSelectorInBackground: @selector(playSong:) withObject: url];
}
Upvotes: 2
Reputation: 2425
Remove timer repeats:Yes to repeats:NO.May be its the problem.Because your gameLoop method would be called after every 0.3 seconds
Upvotes: 0