I have got an AVPlayer setup but I cant seem to get the video audio to continue to play when the phone is locked or on the home screen. I have edited the info.plist and enabled the audio background mode but I think need to add some code. Please could you help me out. Thanks
Here is my code:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
@IBAction func WarmUp(sender: UIButton)
{
WarmUpVideo()
}
func WarmUpVideo()
{
let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "MOV")
let videoURL = NSURL(fileURLWithPath: filePath!)
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
}
}
func playExternalVideo()
{
}
@IBAction func CoolDown(sender: UIButton)
{
CoolDownVideo()
}
func CoolDownVideo()
{
let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "mp4")
let videoURL = NSURL(fileURLWithPath: filePath!)
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
}
}
}
I think you're missing the following code:
do {
try AVAudioSession.sharedInstance()
.setCategory(AVAudioSession.Category.playback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
Add this to your viewDidLoad.
Typical 2019 syntax of the key line of code:
try AVAudioSession.sharedInstance().setCategory(.playback)
In some cases you may want:
try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
You MUST add this ONE item in plist (one item only, beware of old examples);
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Which is:
NOTE: years ago you had to also add UIApplicationExitsOnSuspend - DO NOT add this today.
I found the solution on Apple's Documentation. Additionally to the background modes, you need to set to nil the player in order to avoid auto pause.
Here's the link:
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/creating_a_basic_video_player_ios_and_tvos/playing_audio_from_a_video_asset_in_the_background
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With