CloudKit won't play CKAsset Song Swift 3 - swift

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.

Related

AVFoundation custom video player doesn't display the video?

I'm building a custom video player. To create it, I use play button and view. The video I want to see in the player, I get from the iPhone's Photos. The problem with the player is that I have a working URL of the video, but the view just doesn't display that, actually here is the code of it:`
#IBAction func playVideo(_ sender: Any) {
print("play video")
let videoURL: NSURL = NSURL(string: uurl.url!)!
let player = AVPlayer(url: videoURL as URL)
playerLayerr = AVPlayerLayer(player: player)
playerLayerr.frame = vlogView.bounds
self.vlogView!.layer.addSublayer(playerLayerr)
player.play()
}
The interesting fact is that player finds the video because I can hear the video, but it's not displayed.
Can you try with the bellow code ,it is working for me.
#IBOutlet weak var vlogView: UIView!
var avPlayer = AVPlayer()
var avPlayerLayer: AVPlayerLayer!
#IBAction func playVideo(_ sender: Any) {
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
avPlayerLayer = AVPlayerLayer(player: avPlayer)
self.avPlayerLayer.frame = self.vlogView.frame
avPlayerLayer.videoGravity = .resizeAspectFill
vlogView.layer.insertSublayer(avPlayerLayer, at: 0)
vlogView.layoutIfNeeded()
let playerItem = AVPlayerItem(url: videoURL!)
avPlayer.replaceCurrentItem(with: playerItem)
avPlayer.play()
}

Playing a video saved in document directory [duplicate]

This question already has answers here:
FileManager cannot find audio file
(1 answer)
AVPlayer playerWithURL not working after app restart
(2 answers)
Closed 4 years ago.
I am trying to play a video (.mov) saved in document directory but have failed. The URL of the video was saved into core data. The video file was saved in document directory (I checked it by downloading the directory onto my mac) and I saved the video recorded through my iPhone and saved it as ".MOV". The video was there. The "videourl" in the code returned, "file:///var/mobile/Containers/Data/Application/E45E8260-EA7C-4D30-91AD-D65A208D2057/Documents/myvideo.MOV".
I want to play the video when a user hit the button. When the button was hit, AVplayer shows up but the video is played.
Please help me.
#IBAction func buttonTwoInVmDetailForWatchingAndEditing(_ sender: UIButton) {
print("***********************************")
print(vmIDInWatchingAndEditingViewController)
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "TaskAnalysisURL")
let predicateWithVmIDInVideoPhotoView = NSPredicate(format: "vmID == %#", vmIDInWatchingAndEditingViewController as CVarArg)
fetchRequest.predicate = predicateWithVmIDInVideoPhotoView
do { //try context.fetch(Users.fetchRequest())
let taskAnalysisURLsSelected = try context.fetch(fetchRequest)
let taskAnalysisURLsSelectedTofetch = taskAnalysisURLsSelected as! [TaskAnalysisURL]
if taskAnalysisURLsSelectedTofetch.count == 0 {
print("================== if ================")
print(taskAnalysisURLsSelectedTofetch.count)
} else {
print("================== else ================")
print(taskAnalysisURLsSelectedTofetch.count)
for taskAnalysisURLSelectedTofetch in taskAnalysisURLsSelectedTofetch as [NSManagedObject] {
let stepTwoURLToPlayVideo = taskAnalysisURLSelectedTofetch.value(forKey: "stepTwoURL")
print("===========URL=============")
print(stepTwoURLToPlayVideo!)
let videoUrl = "file://\(String(describing: stepTwoURLToPlayVideo!))"
print(videoUrl)
let videourl = URL(fileURLWithPath: stepTwoURLToPlayVideo! as! String)
print("#########################")
print(videourl)
let player = AVPlayer(url: videourl) // video path coming from above function
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
let playerItem = AVPlayerItem(url: videourl)
let playerTwo = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: playerTwo)
playerLayer.frame = self.view.frame
self.view.layer.addSublayer(playerLayer)
playerViewController.player!.play()
}
}
}
}
catch {
print(error.localizedDescription)
}
}

AVPlayer takes lot of time to start playing song from url

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 :|

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
}
}