Created
September 17, 2015 16:40
-
-
Save tinyhappysteps/ce135799b38a54dae57a to your computer and use it in GitHub Desktop.
Swift Resume Audio AVFoundation - AVQueuePlayer AVPlayer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you should use notification center callback
work for me: https://stackoverflow.com/questions/54971492/how-can-i-resume-the-mp4-video-after-transition-from-the-background-to-the-activ