Skip to content

Instantly share code, notes, and snippets.

@tinyhappysteps
Created September 17, 2015 16:40
Show Gist options
  • Save tinyhappysteps/ce135799b38a54dae57a to your computer and use it in GitHub Desktop.
Save tinyhappysteps/ce135799b38a54dae57a to your computer and use it in GitHub Desktop.
Swift Resume Audio AVFoundation - AVQueuePlayer AVPlayer
import UIKit
import AVFoundation
var player: AVQueuePlayer!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers )
try AVAudioSession.sharedInstance().setActive(true, withOptions: .NotifyOthersOnDeactivation)
} catch { print("initial crapped out")}
let songNames = ["music"]
let songs = songNames.map { AVPlayerItem(URL:
NSBundle.mainBundle().URLForResource($0, withExtension: "mp3")!) }
player = AVQueuePlayer(items: songs)
let theSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self,
selector:"playInterrupt:",
name:AVAudioSessionInterruptionNotification,
object: theSession)
player.play()
}
func playInterrupt(notification: NSNotification) {
if notification.name == AVAudioSessionInterruptionNotification
&& notification.userInfo != nil {
var info = notification.userInfo!
var intValue: UInt = 0
(info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
if let type = AVAudioSessionInterruptionType(rawValue: intValue) {
switch type {
case .Began:
print("Interruption began")
player.pause()
case .Ended:
print("Interruption ended")
_ = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "resumeNow:", userInfo: nil, repeats: false)
}
}
}
}
func resumeNow(timer : NSTimer) {
print("Attempting restart")
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("It crapped out")
print(error)
}
player.play()
}
}
@trunghieuvn
Copy link

you should use notification center callback

NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(enteredForeground), name: UIApplication.willEnterForegroundNotification, object: nil)


  @objc func enteredBackground() {
        playerController.player?.pause()
    }

    @objc func enteredForeground() {
       playerController.player?.play()
    }

work for me: https://stackoverflow.com/questions/54971492/how-can-i-resume-the-mp4-video-after-transition-from-the-background-to-the-activ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment