AVPlayer takes lot of time to start playing song from url - swift

im new to swift development.Im working on a music player app.
Im using AVPlayer to stream music from url. It is playing music fine.But it takes a lot of time to start playing. I searched a lot and none of the solutions worked for me. im adding the code im using below.
func playMusic(){
player?.replaceCurrentItem(with: nil)
let url = NSURL(string: musicURL )
playerItem = AVPlayerItem(url: url! as URL)
player = AVPlayer(playerItem: playerItem!)
playerLayer = AVPlayerLayer(player: player)
if player?.rate != nil{
player?.play()
// player?.playImmediately(atRate: 1.0)
player?.volume = 1.0
isPlayingDownloadedSong = false
didAVStreamingPlayerPlayedOnce = true
isSongLoading = true
//to get duration only once
didGetDurationOfCurrentSong = false
didGetDuration = false
self.startLoader()
musicObserver.playerTimeObserver()
self.didLoaderTurnedOff = false
// this is for player page
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "startLoader"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch{
print("some error happened")
}
self.playBtnInMusicPlayer.setImage( imageLiteral(resourceName: "pause"), for: .normal)
self.musicNameLabelInMusicPlayer.text = songName
}
}
i have added the both these codes.
automaticallyWaitsToMinimizeStalling = false
automaticallyWaitsToMinimizeStalling = true
player?.playImmediately(atRate: 1.0)
tried both of the above lines
But none of them works for me . Please help me with this

Do check if you are in a network where scanning is enabled. if yes, try whitelisting the play url.
Note: The above should be a comment but reputation matters :|

Related

AV Player view controller not closing

I updated to iOS 12 and the AV Player VC close button don't work anymore. The screen never dismissed, it pause the video instead. This actions was working just fine on previous iOS versions.
Is there any particular reason for this?
EDIT: Added code
guard let movieURL = URL(string: urlStr) else { return }
moviePlayer = AVPlayer(url: movieURL)
self.moviePLayerViewController.player = moviePlayer
moviePLayerViewController.view.frame = vwMainContainer.bounds
moviePLayerViewController.modalTransitionStyle = .crossDissolve
moviePLayerViewController.modalPresentationStyle = .overCurrentContext
present(moviePLayerViewController, animated: true) {
self.moviePlayer?.play()
}
You didn't showed any Code there
Just try the following method It just work perfectly fine for me
//MARK: Play Video At Index Path
func playVideoWith(_ videoURL: URL) {
let player = AVPlayer(url: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
playerViewController.view.frame = self.view.frame
self.present(playerViewController, animated: true) {
playerViewController.player?.play()
}
}
Note - Please show code So, we can see where the mistake is else just try above code once and let me know did it helped ?
It is resolved now, I just removed the modal presentation style and worked again. I am not sure why this was a problem, if anyone know pleas answer.
guard let movieURL = URL(string: urlStr) else { return }
moviePlayer = AVPlayer(url: movieURL)
self.moviePLayerViewController.player = moviePlayer
moviePLayerViewController.view.frame = vwMainContainer.bounds
present(moviePLayerViewController, animated: true) {
self.moviePlayer?.play()
}

AVPlayer works on simulator but crashes on real device

AVPlayer is working fine in simulator but crashes on device.totally stuck please help out.
override func viewDidAppear(animated: Bool) {
let fileURL = NSURL(string: NSUserDefaults.standardUserDefaults().objectForKey("introVideoURl") as! String)
playVideo(fileURL!) // crashing line
}
func playVideo(url: NSURL) throws-> AnyObject{
let player = AVPlayer(URL: url)
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(introVideoController.playerDidFinishPlaying(_:)),
name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)
player.play()
return true
}

CloudKit won't play CKAsset Song Swift 3

I have a song stored in CloudKit as a CKAsset. I successfully retrieve the song and get no error but it just won't play. Any help would be appreciated, thanks.
My AVPlayer is lazily instantiated within the class.
//Create song player to play song, lazily instantiated
lazy var songPlayer: AVPlayer = {
let player = AVPlayer()
return player
}()
func playPause() {
//Unwrap song - if there is no song, then return...you can't play something that is not there.
guard let song = selectedArtist.song else {
return
}
//Create player item
let playerItem = AVPlayerItem(url: song.fileURL)
//Add observer so app knows when the song reached its end
NotificationCenter.default.addObserver(
self,
selector: #selector(itemDidFinishPlaying(notification:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: playerItem)
//Assign playerItem to AVPlayer
songPlayer = AVPlayer(playerItem: playerItem)
if isSongPlaying {
print("Song at \(song.fileURL) stopped.")
isSongPlaying = false;
songPlayer.pause()
songPlayPauseImageView.image = UIImage(named: "play.png")
} else {
print("Song at \(song.fileURL) started.")
isSongPlaying = true;
songPlayer.play()
songPlayPauseImageView.image = UIImage(named: "pause.png")
}
}
When I start playing the song I get the message (as expected):
Song at file:///private/var/mobile/Containers/Data/Application/E34BE227-86DD-4AD7-A3C1-6A0610CE8C39/Library/Caches/CloudKit/6e22c352bc4bdeb0b75d42a0d681d67c69eeaad4/Assets/6BD84822-D039-4228-A5E9-59CB281BB964.0182fa97976e7d7b941bb8d8790ea75c6d3b72c302 started.
Unfortunately, the song doesn't play.

NSNotificationCenter to AVQueuePlayer in swift

I added list of AVQueuePlayer to UITableViewCell. I added array of videos to AVQueuePlayer as follows:
if let urls = delegate.arrayVideofeedItemsList[indexPath.row] as? NSArray
{
let player = AVQueuePlayer()
for currentVideoObject in urls {
let avAsset = AVURLAsset(URL: NSURL(fileURLWithPath: "\(currentVideoObject)"))
avAsset.loadValuesAsynchronouslyForKeys(["playable", "tracks", "duration"], completionHandler: {
dispatch_async(dispatch_get_main_queue(), {
// self.enqueue(avAsset)
let item = AVPlayerItem(asset: avAsset)
player.insertItem(item, afterItem: nil)
})
})
}
let playerLayer = AVPlayerLayer(player: player)
// playerLayer.backgroundColor = UIColor.greenColor().CGColor
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
playerLayer.frame = CGRectMake(0, 0,SCREEN_WIDTH, 250)
cell.contentView.layer.addSublayer(playerLayer)
player.play()
player.actionAtItemEnd = AVPlayerActionAtItemEnd.Advance
player.volume = 0.0
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification,object:player.currentItem)
}
func playerItemDidReachEnd(notification: NSNotification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seekToTime(kCMTimeZero)
}
I have three videos in AVQueuePlayer. Three videos are played sequentially but After completion of this first video is not playing. What I need to add to this ? Please help me to complete it.
Try to add this line after initializing player:
player.actionAtItemEnd = AVPlayerActionAtItemEnd.None

How to detect SKVideoNode playback completion

I am using an SKVideoNode to display animated splash scene using this code:
SKVideoNode *video = [SKVideoNode videoNodeWithVideoFileNamed:#"splash_video.mp4"];
video.position = CGPointMake(CGRectGetMidX(self.frame),
CGRectGetMidY(self.frame));
[self addChild:video];
[video play];
I wish to display the next scene once video playback is done. How can I achieve that?
Add this to your viewDidLoad or elsewhere suitable
let videoURL = NSURL(string: url)
let player = AVPlayer(URL: videoURL!)
player.actionAtItemEnd = .None
let videoSpriteKitNode = SKVideoNode(AVPlayer: player)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)
And add this function:
func playerItemDidReachEnd(notification: NSNotification) {
if let playerItem = notification.object as? AVPlayerItem {
//Start your next video here
}
}