开发者

Using AVAudioPlayer in a UIViewController

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 allo开发者_StackOverflowc] 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?


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];
}


Remove timer repeats:Yes to repeats:NO.May be its the problem.Because your gameLoop method would be called after every 0.3 seconds

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜