Play audio while downloading without downloading file twice? - ios

I would like to write an iOS app that plays an audio file as soon as there is enough data while continuing to download. It seems that you can either download and play when the download is finishing (Using NSURLProtocol to implement play while downloading for AVPlayer on iOS) or continuously stream without getting to save a file (Playing audio file while I download it). Is there any way to download and play at the same time without downloading two copies of the file?

You can do that with the help of AVAssetResourceLoader and AVPlayer
Here is the link of the tutorial
http://leshkoapps.com/wordpress/audio-streaming-and-caching-in-ios-using-avassetresourceloader-and-avplayer/
And here is the Github repo for that
https://github.com/leshkoapps/AVAssetResourceLoader

here you can use below functions without download (Streaming)
import AVFoundation
var progressTimer:Timer?
{
willSet {
progressTimer?.invalidate()
}
}
var playerStream: AVPlayer?
var playerItem: AVPlayerItem?
func playerStream(urlStream : String)
{
if let playerStream = playerStream
{
if playerStream.isPlaying
{
stopProgressTimer()
playerStream.pause()
}
else
{
startProgressTimer()
playerStream.play()
}
}
else
{
if let urlStr = urlStream.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
{
if let TempURL = URL.init(string: urlStr)
{
playerItem = AVPlayerItem(url: TempURL)
playerStream = AVPlayer(playerItem: playerItem)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
}
}
}
}
func playerItemDidPlayToEndTime() {
stopProgressTimer()
self.playProgressView.progress = 0.0
if let playerStream = self.playerStream
{
playerStream.replaceCurrentItem(with: playerItem)
playerStream.seek(to: kCMTimeZero)
// playerStream.seek(to: .zero) swift 4.0
}
}
func stopProgressTimer() {
progressTimer?.invalidate()
progressTimer = nil
}
func startProgressTimer()
{
if #available(iOS 10.0, *) {
progressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){_ in
self.updateProgressTimer()
}
}
else {
progressTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateProgressTimer), userInfo: nil, repeats: true)
}
}
#objc func updateProgressTimer()
{
if let playerItem = playerItem
{
if let pa = playerStream
{
let floatTime = Float(CMTimeGetSeconds(pa.currentTime()))
let floatTimeDu = Float(CMTimeGetSeconds(playerItem.duration))
playProgressView.progress = Double(floatTime / floatTimeDu)
}
}
}

Related

Resuming AVPlayer after phone call

There appears to be many solutions on SO addressing this yet none of those solutions have worked for me. I'm currently using Swift 5. I have a AVPlayer playing an animation (that loops) in my ViewController. When a call comes in through CallKit, regardless of whether I answer or decline the call, the animation played by the AVPlayer does not resume after the call has been dealt with. The interruption handler seems to be called before an interruption but usually doesn't get called after the interruption.
override func viewDidLoad() {
super.viewDidLoad()
prepareBGVideo()
...
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationWillEnterForeground(notification:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
...
}
func prepareBGVideo() {
guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
print("video not found")
return
}
let item = AVPlayerItem(url: URL(fileURLWithPath: path))
avPlayer = AVPlayer(playerItem: item)
NotificationCenter.default.addObserver(self,
selector: #selector(loopVideoBG),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: item)
NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.backgroundColor = UIColor.black.cgColor
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
avPlayer.play()
view.backgroundColor = .clear
avPlayerLayer.frame = view.layer.bounds
view.layer.insertSublayer(avPlayerLayer, at: 0)
avPlayerLayer.videoGravity = isIPAD ? AVLayerVideoGravity.resize : AVLayerVideoGravity.resizeAspectFill // Changed from AVLayerVideoGravity.resizeAspect to AVLayerVideoGravity.resize so that video fits iPad screen
NotificationCenter.default.addObserver(self,
selector: #selector(willEnterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
#objc func handleInterruption(notification: Notification) {
guard let info = notification.userInfo,
let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}
if type == .began {
// Interruption began, take appropriate actions (save state, update user interface)
self.avPlayer.pause()
} else if type == .ended {
guard let optionsValue =
info[AVAudioSessionInterruptionOptionKey] as? UInt else {
return
}
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// Interruption Ended - playback should resume
self.avPlayer.play()
}
}
}
/// Resume video while app wake up from background
#objc func willEnterForeground() {
avPlayer.seek(to: CMTime.zero)
JPUtility.shared.performOperation(0.1) {
self.avPlayer.play()
}
}
#objc func loopVideoBG() {
avPlayer.seek(to: CMTime.zero)
avPlayer.play()
}
Here are all the solutions that I have tried:
Waiting two seconds before calling self.avPlayer.play() in if options.contains(.shouldResume){}
Setting AVAudioSession.sharedInstance().setActive to false when interruption begins and then setting it ot true when interruption ends. The issue with this approach is that the if interruption == .ended {} block doesn't always get invoked so setting setActive had no effect.
Setting AVAudioSession playback category to AVAudioSessionCategoryOptions.MixWithOthers. My animation doesn't have audio anyway.
I have seen mentions of resuming playback in applicationDidBecomeActive(_:) but some advised against this. Would this be considered good practice?
Is there a way to ensure that the else if type == .ended {} block gets executed? Or perhaps a workaround that works more reliably than observing AVAudioSession.interruptionNotification?
I solved this but creating a shared VideoPlayer class that contained references to all the screen that had animations.
import Foundation
import UIKit
import AVKit
class VideoPlayer: NSObject {
static var shared: VideoPlayer = VideoPlayer()
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
weak var vcForConnect:ConnectVC?
weak var vcForList:ListVC?
override init() {
super.init()
guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
print("video not found")
return
}
avPlayer = AVPlayer(url: URL(fileURLWithPath: path))
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
loopVideo(videoPlayer: avPlayer)
avPlayer.play()
NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)
}
deinit {
avPlayer.pause()
}
#objc func handleInterruption(notification: Notification) {
guard let info = notification.userInfo,
let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}
if type == .began {
// Interruption began, take appropriate actions (save state, update user interface)
self.avPlayer.pause()
} else if type == .ended {
guard let optionsValue =
info[AVAudioSessionInterruptionOptionKey] as? UInt else {
return
}
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// Interruption Ended - playback should resume
self.avPlayer.play()
}
}
}
func resumeAllAnimations() {
self.avPlayer.play()
if vcForList?.avPlayer != nil {
vcForList?.avPlayer.play()
}
if vcForConnect?.avPlayer != nil {
vcForConnect?.avPlayer.play()
}
if vcForConnect?.avPlayerBG != nil {
vcForConnect?.avPlayerBG.play()
}
}
...
}
I then resume the animations by calling resumeAllAnimations() in applicationDidBecomeActive(_:) in AppDelegate.swift like so:
func applicationDidBecomeActive(_ application: UIApplication) {
VideoPlayer.shared.resumeAllAnimations()
...
}

Autopan in iOS with AVAudioPlayer smoothly

I am trying to build autopan(move the audio between left, middle and right channel) with AVaudioPlayer to play my music files. I could get it through AVAudioPlayer.pan method. Implemented to get AUTO pan by using timer in my swift code. Now the issue is ,audio is not playing smoothly and it breaks in between.
Here is my present code ,
class AudioPlayer: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioSession()
}
func prepareAudioSession() {
let audioFileName = "LPNumb"
let audioFileExtension = "mp3"
guard let filePath = Bundle.main.path(forResource: audioFileName, ofType: audioFileExtension) else {
print("Audio file not found at specified path")
return
}
do {
let alertSound = URL(fileURLWithPath: filePath)
try? player = AVAudioPlayer(contentsOf: alertSound)
} catch {
print(error)
}
}
#IBAction func play(_ sender: AnyObject){
player.play()
if player.isPlaying{
_ = Timer.scheduledTimer(timeInterval: 0.50, target: self, selector: #selector(self.update1), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.update2), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 1.50, target: self, selector: #selector(self.update3), userInfo: nil, repeats: true)
}
}
#objc func update1() {
player.pan = 0
}
#objc func update2() {
player.pan = 1
}
#objc func update3() {
player.pan = -1
}
}
I want to make the output audio as MONO and require audio to be played AUTOPANNED smoothly.
I think, you need make just one Timer for this task.Take a look through the code:
import UIKit
import AVFoundation
enum PanState {
case up
case down
}
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
var timerForPan: Timer?
var pan: Double = 0.0
var panState: PanState = .up
override func viewDidLoad() {
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "LPNumb", ofType: "mp3") {
let record = URL(fileURLWithPath: path)
setupRecordToPlayer(from: record)
}
setTimers()
}
func setTimers() {
timerForPan = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updatePan), userInfo: nil, repeats: true)
}
func setupRecordToPlayer(from url: URL) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch let error {
debugPrint(error.localizedDescription)
}
}
#IBAction func playButtonPressed(_ sender: UIButton) {
audioPlayerToPlay()
}
#objc func updatePan() {
if audioPlayer?.isPlaying ?? false {
switch panState {
case .up:
self.pan += 0.1
if pan >= 1 {
self.panState = .down
}
case .down:
self.pan -= 0.1
if pan <= -1 {
self.panState = .up
}
}
audioPlayer?.pan = Float(self.pan)
}
}
/// Prepare Audio player to play
func audioPlayerToPlay() {
audioPlayer?.prepareToPlay()
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} catch {
print(error.localizedDescription)
}
audioPlayer?.play()
}
}

AVPlayer keeps adding streams instead of replacing

I am triggering a video play from a URL. It's just a button, opening the AVPlayerController full screen. If people close it, the can go back to the another item, with possibly a video. There they can click that video to start, however, when they do so, I can hear the audio of the previous player, of the other VC playing in the together with this one. This keeps layering up. How can I avoid this?
This is my class for the videoplayer
import UIKit
import AVFoundation
import AVKit
class simpleVideoPlayer: UIViewController {
var playerController = AVPlayerViewController()
var player:AVPlayer?
var inputVideoUrl: String? = nil
func setupVideo() {
self.player = AVPlayer()
self.playerController.player = self.player
}
func playNext(url: URL) {
let playerItem = AVPlayerItem.init(url: url)
self.playerController.player?.replaceCurrentItem(with: playerItem)
self.playerController.player?.play()
}
func setupVideoUrl(url: String) {
inputVideoUrl = url
}
}
This is in my viewcontroller. It's first getting a URL of a possible advert from my server, if that failed, then it wil just load the "default" video.
let SimpleVideo = simpleVideoPlayer()
#objc func handleTap(gestureRecognizer: UIGestureRecognizer)
{
ApiVideoAdvertService.sharedInstance.fetchVideoAdvert { (completion: VideoAdvert) in
let advertUrl = URL(string: completion.video_adverts_url)
var url = URL(string: (self.article?.video_link?.files[0].link_secure)!)
var showAdvert: Bool = false
if (advertUrl != nil && UIApplication.shared.canOpenURL(advertUrl!)) {
url = advertUrl
showAdvert = true
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if (showAdvert) {
NotificationCenter.default.addObserver(self, selector: #selector(self.finishVideo),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.SimpleVideo.playerController.player?.currentItem)
}
appDelegate.window?.rootViewController?.present(self.SimpleVideo.playerController, animated: true, completion: {
self.SimpleVideo.setupVideo()
if (showAdvert) {
self.SimpleVideo.playerController.setValue(true, forKey: "requiresLinearPlayback")
}
self.SimpleVideo.playNext(url: url!)
})
}
#objc func finishVideo() {
let url = URL(string: (article?.video_link?.files[0].link_secure)!)
SimpleVideo.playerController.setValue(false, forKey: "requiresLinearPlayback")
SimpleVideo.playNext(url: url!)
}
Removing the observer inside finishVideo did it.
#objc func finishVideo() {
NotificationCenter.default.removeObserver(self)
let url = URL(string: (article?.video_link?.files[0].link_secure)!)
SimpleVideo.playerController.setValue(false, forKey: "requiresLinearPlayback")
SimpleVideo.playNext(url: url!)
}

AVPlayer progress with UISlider Swift

I'm trying to use a slider to control Audio and everything works fine, but when I try to make the slider value equal to the player current time it crashes.
However, if I print something inside the updateSlider function, it appears and works fine.
override func viewDidLoad()
{
songTitle.text = mainSongTitle
background.image = image
mainImageView.image = image
downloadFileFromURL(url: URL(string: previewURL)!)
var time = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
}
func downloadFileFromURL(url : URL)
{
var downloadTask = URLSessionDownloadTask()
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler:
{
customURL , response , error in
self.play(url: customURL!)
self.slider.maximumValue = Float(player.duration)
})
downloadTask.resume()
}
func play(url : URL)
{
do
{
player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.play()
}
catch
{
print(error)
}
}
#IBAction func PlayPressed(_ sender: Any)
{
if player.isPlaying
{
player.pause()
}
else
{
player.play()
}
}
#IBAction func ChangerTimePlayer(_ sender: Any)
{
player.stop()
player.currentTime = TimeInterval(slider.value)
player.prepareToPlay()
player.play()
}
func updateSlider()
{
slider.value = Float(player.currentTime)
}
Maybe you should do something like:
func updateSlider(){
slider.value = Float(player.currentTime/player.duration)
}
Your download completion task needs to be called on the main thread to safely use UIKit (your slider):
DispatchQueue.main.async {
self.play(url: customURL!)
self.slider.maximumValue = Float(player.duration)
}

Audio playback progress as UISlider in Swift

I've seen some posts about accomplishing this in Objective-C but I've been unable to do the same via Swift.
Specifically, I can't figure out how to implement addPeriodicTimeObserverForInterval in the below.
var player : AVAudioPlayer! = nil
#IBAction func playAudio(sender: AnyObject) {
playButton.selected = !(playButton.selected)
if playButton.selected {
let fileURL = NSURL(string: toPass)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.numberOfLoops = -1 // play indefinitely
player.prepareToPlay()
player.delegate = self
player.play()
startTime.text = "\(player.currentTime)"
endTime.text = NSString(format: "%.1f", player.duration)
} else {
player.stop()
}
Any assistance would be appreciated.
Thanks to the suggestion of Dare above, here's how I accomplished this:
var updater : CADisplayLink! = nil
#IBAction func playAudio(sender: AnyObject) {
playButton.selected = !(playButton.selected)
if playButton.selected {
updater = CADisplayLink(target: self, selector: Selector("trackAudio"))
updater.frameInterval = 1
updater.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
let fileURL = NSURL(string: toPass)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.numberOfLoops = -1 // play indefinitely
player.prepareToPlay()
player.delegate = self
player.play()
startTime.text = "\(player.currentTime)"
theProgressBar.minimumValue = 0
theProgressBar.maximumValue = 100 // Percentage
} else {
player.stop()
}
}
func trackAudio() {
var normalizedTime = Float(player.currentTime * 100.0 / player.duration)
theProgressBar.value = normalizedTime
}
#IBAction func cancelClicked(sender: AnyObject) {
player.stop()
updater.invalidate()
dismissViewControllerAnimated(true, completion: nil)
}
Just to elaborate on my previous comment, this is how I implemented it and it seems to work pretty well. Any Swift corrections are more than welcome, I'm still an Obj-C guy for now.
#IBAction func playAudio(sender: AnyObject) {
var playing = false
if let currentPlayer = player {
playing = player.playing;
}else{
return;
}
if !playing {
let filePath = NSBundle.mainBundle().pathForResource("3e6129f2-8d6d-4cf4-a5ec-1b51b6c8e18b", ofType: "wav")
if let path = filePath{
let fileURL = NSURL(string: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.numberOfLoops = -1 // play indefinitely
player.prepareToPlay()
player.delegate = self
player.play()
displayLink = CADisplayLink(target: self, selector: ("updateSliderProgress"))
displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode!)
}
} else {
player.stop()
displayLink.invalidate()
}
}
func updateSliderProgress(){
var progress = player.currentTime / player.duration
timeSlider.setValue(Float(progress), animated: false)
}
*I set time slider's range between 0 and 1 on a storyboard
Specifically for Swift I was able to handle it like this:
I set the maximum value of the scrubSlider to the duration of the music file(.mp3) that was loaded in this method
override func viewDidLoad() {
super.viewDidLoad()
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bach", ofType: "mp3")!))
scrubSlider.maximumValue = Float(player.duration)
} catch {
//Error
}
_ = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.updateScrubSlider), userInfo: nil, repeats: true)
}
I player was set to play the music at the time set by the value of the scrubber.
#IBAction func scrub(sender: AnyObject) {
player.currentTime = NSTimeInterval(scrubSlider.value)
}
Syntax has now changed in Swift 4:
updater = CADisplayLink(target: self, selector: #selector(self.trackAudio))
updater.preferredFramesPerSecond = 1
updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
And the function (I have previously set the progressSlider.maxValue to player.duration):
#objc func trackAudio() {
progressSlider.value = Float(player!.currentTime)
}

Resources