Note that there are some explanatory texts on larger screens.

plurals
  1. POSuper quick AVPlayer init or how to start it in background?
    text
    copied!<p>Scenario:</p> <p>App is for streaming music from radio station. I'm using AVPlayer for this. App can play music in background (<code>Required background modes</code> in plist), App can receive play/pause action from locked screen (with using <code>AVAudioSessionDelegate</code> and <code>remoteControlReceivedWithEvent</code> method). And this part is ok.</p> <p><strong>Problem</strong></p> <p>User starts app. When first screen is loaded user tap on "Play" button. Now, in my code, AVPlayer is initialized and as soon as this task is ready it's starting to play music. But this task last for something like 3 to 5 second even on quick Wi-Fi.</p> <p>Of course in that 3-5 seconds user can tap on Home Button, app is going to background and AVPlayer never starts to play audio.</p> <p>How can I handle this? I tried to run <code>[avplayer play]</code> in <code>dispatch_async</code> but it didn't help. I also tried to initialize AVPlayer in AppDelegate, and now audio is loading faster, but still, user can be quicker... What kind of approach to solve this problem is proper?</p> <p><strong>Update - code for initializing player</strong></p> <p>in header file (MainViewController): //MyPlayer is subclass of AVPlayer</p> <p><code>@property (nonatomic, strong) MyPlayer *playerBrain;</code></p> <p>implementation file:</p> <pre><code>//lazy instantiation - (MyPlayer*)playerBrain { if (_playerBrain == nil) _playerBrain = [[MyPlayer alloc] initWithURL:[NSURL URLWithString:@"correct_URL_To_MP3_File"]]; return _playerBrain; } - (IBAction)onOffSwitch:(UISwitch *)sender { if (sender.isOn) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSLog(@"inside block!"); [self.playerBrain playRadio]; }); } else { [self.playerBrain pause]; } } </code></pre> <p>//inside MyPlayer implementation</p> <pre><code>- (void)playRadio { [self play]; //this is method from parent, AVPlayer } </code></pre>
 

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