Note that there are some explanatory texts on larger screens.

plurals
  1. POAVAudioPlayer cannot play music with a NSTimer in background
    primarykey
    data
    text
    <p>I want to play music with an AVAudioPlayer using an NSTimer, but <code>[player prepareToPlay]</code> returns NO &amp; doesn't play in the background.</p> <p>Can somebody give me some idea?</p> <p>Here's my code:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO]; [self.window makeKeyAndVisible]; return YES; } - (void)playMusic:(NSTimer *)timer{ [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"]; NSURL *fileUrl = [NSURL fileURLWithPath:fileName]; NSError *error; AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&amp;error]; if ([player prepareToPlay]) { [player play]; NSLog(@"start!"); }else{ NSLog(@"error msg :%@",error); } } - (void)applicationDidEnterBackground:(UIApplication *)application { if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; } UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ // /* just fail if this happens. */ [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; }]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload