How do I play 30 seconds of an avplayeritem? - ios

I can play the whole entire song, but I want to only play 30 seconds of it. How would I do that?
if let url: String = "hiddingthelink"{
let urlplayer = NSURL(string: url)
let playeritem = AVPlayerItem(URL:(urlplayer)!)
player = AVPlayer(playerItem: playeritem)
self.player.volume = 1.0
self.player.rate = 1.0
self.player.play()
}

Related

Unable to play streaming audio

I want to play streaming audio on an iOS app. I use this code to play audio:
let url = URL(string: "http://online.radiorecord.ru:8102/chil_320.m3u")!
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer.init(playerItem: playerItem)
player.play()
When I run the app on the Simulator I get this error:
2018-11-30 21:57:26.097577+0300 radio[7417:21800733]
[AudioHAL_Client]
AudioHardware.cpp:1210:AudioObjectRemovePropertyListener:
AudioObjectRemovePropertyListener: no object with given ID 0
How to fix this issue?
var player: AVPlayer?
let url = URL(string: "http://online.radiorecord.ru:8102/chil_320.m3u")!
player = AVPlayer(url: url)
player?.play()

AVPlayerViewController issue with iOS 12

I'm using AVPlayerViewController for playing video it works fine with iOS 11 but the same code doesn't work in iOS 12. could anyone help me to fix this issue please?
let url: URL = Bundle.main.url(forResource: "sampleVideo", withExtension: ".mp4")!
let avAsset = AVURLAsset(url: url)
let playerItem = AVPlayerItem(asset: avAsset)
player = AVPlayer(playerItem: playerItem)
playerController = AVPlayerViewController()
playerController?.player = player
playerController?.view.frame = videoHolderView?.bounds ?? CGRect.zero
guard let videoView = playerController?.view else { return }
videoView.tag = 101
videoHolderView.addSubview(videoView)
player?.play()
Finally figured out the issue!!!
in iOS 12 if you disable PlayBackControls of AVPlayerController, AVPlayer will still consume the tap gesture.
playerController?.showsPlaybackControls = false

AVPlayerViewController Showing Black Screen

I am trying to play a video in AVplayer with below code but it's showing black screen.I also tried googling but didn't get any luck
let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let asset = AVURLAsset(url: url!)
let item = AVPlayerItem(asset: asset)
let player = AVPlayer.init(playerItem: item)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
I also added plist entry for TransportSecurity.

m3u8 not playing offline - swift 3.0

I am trying to stream an m3u8 url and save offline.
Then play from offline.
I am using Apple HTTP Live Streaming
Start Download by using the below code
func setupAssetDownload() {
// Create new background session configuration.
configuration = URLSessionConfiguration.background(withIdentifier: DOWNLOAD_ID)
// Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
downloadSession = AVAssetDownloadURLSession(configuration: configuration,
assetDownloadDelegate: self,
delegateQueue: OperationQueue.main)
let url = URL(string: urlString)
let asset = AVURLAsset(url: url!)
// Create new AVAssetDownloadTask for the desired asset
let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset, assetTitle: "asset_Title", assetArtworkData: nil, options: nil)
// Start task and begin download
downloadTask?.resume()
}
Where,
let DOWNLOAD_ID = "downloadIdentifier"
let urlString = "http://domain/vod/mp4:sample1.mp4/playlist.m3u8"
// Saving the Download Location
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
print("didFinishDownloadingTo \(location.relativePath)")
// Do not move the asset from the download location
UserDefaults.standard.set(location.relativePath, forKey: "assetPath")
}
When try to play Offline,
I can get the AVURLAsset,
<AVURLAsset: 0x1742319e0, URL = file:///var/mobile/Containers/Data/Application/79C0043F-6161-4231-9129-B71C95903E05/Library/com.apple.UserManagedAssets.bhVNRN/asset_Title_63128673BE57FBDD.movpkg/>
But, not paying from the asset.
func playOfflineAsset() {
guard let assetPath = UserDefaults.standard.value(forKey: "assetPath") as? String else {
// Present Error: No offline version of this asset available
return
}
let baseURL = URL(fileURLWithPath: NSHomeDirectory())
let assetURL = baseURL.appendingPathComponent(assetPath)
let asset = AVURLAsset(url: assetURL)
let player = AVPlayer(url:assetURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = videoView2.bounds
playerLayer.backgroundColor = UIColor.purple.cgColor
videoView2.layer.addSublayer(playerLayer)
player.play()
if let cache = asset.assetCache, cache.isPlayableOffline {
// Set up player item and player and begin playback
print("exist")
} else {
// Present Error: No playable version of this asset exists offline
print("doesn't exist")
}
}
you need add AVPlayerController to AVPlayer can play with sounds, i dont know why, but its work for me
// Set up player item and player and begin playback
let playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)
// play without present playerController
self.player?.play()
// play with present playerController
// let playerController = AVPlayerViewController()
// playerController.player = player
// self.present(playerController, animated: true) {
// self.player?.play()
// }
Edit: Make sure hls not encrypt.

swift 3 Avplayer layer not visible while playing same video second time

In my application I have used AVPlayer to play videos, If we play a video and go bock to previous page video is playing in backgraound well but if we play the same video again we have to show continuation of the video and it should not begin from start , Here I can able to set slider position according to the video duration but the screen not showing video content sound is coming.
For first time to play any video i called below method
func setup() {
UserDefaults.standard.set(videoString as NSString, forKey: CurrentURL)
UserDefaults.standard.synchronize()
let targetTime:CMTime = CMTimeMake(0, 1)
mediaPlayer.seek(to: targetTime)
mediaPlayer.pause()
print("Video URL \(videoString)")
let url = NSURL(string: videoString)
let playerItem = AVPlayerItem(url: url! as URL)
mediaPlayer=AVPlayer(playerItem: playerItem)
let playerLayer=AVPlayerLayer(player: mediaPlayer)
playerLayer.frame = self.view.bounds
playerLayer.backgroundColor = UIColor.black.cgColor
//playerLayer.videoGravity = AVLayerVideoGravityResize
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
self.view.layer.addSublayer(playerLayer)
AppDelegate.shared().showLoading()
videoView.isHidden = false
mediaPlayer.play()
let duration : CMTime = mediaPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
videoSlider.maximumValue = Float(seconds)
videoPlayButton.setImage(UIImage(named: "Pause"), for: .normal)
videoPlaying = true
//Adding Default Periodic Observer On Player
mediaPlayer.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if mediaPlayer.currentItem?.status == .readyToPlay {
AppDelegate.shared().removeLoading()
self.videoSlider.value = Float(CMTimeGetSeconds(mediaPlayer.currentTime()))
let currentTime : Int = Int(CMTimeGetSeconds(mediaPlayer.currentTime()))
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
self.durationLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
}
}
}
If user plays same video second time i'm checking current url which is stored in userdefaults if it is playing same video i did like following
let runningSrtring = UserDefaults.standard.object(forKey: CurrentURL) as! NSString
if runningSrtring.isEqual(to: videoString) {
//self.view.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
videoPlayButton.setImage(UIImage(named: "Pause"), for: .normal)
let duration : CMTime = mediaPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
self.videoSlider.value = Float(CMTimeGetSeconds((mediaPlayer.currentTime())))
videoSlider.minimumValue = 0
videoSlider.maximumValue = Float(seconds)
let playerLayer = AVPlayerLayer(player: mediaPlayer)
playerLayer.frame = self.view.frame
playerLayer.backgroundColor = UIColor.black.cgColor
//playerLayer.videoGravity = AVLayerVideoGravityResize
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
self.view.layer.addSublayer(playerLayer)
mediaPlayer.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if mediaPlayer.currentItem?.status == .readyToPlay {
self.videoSlider.value = Float(CMTimeGetSeconds((mediaPlayer.currentTime())))
let currentTime : Int = Int(CMTimeGetSeconds(mediaPlayer.currentTime()))
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
self.durationLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
}
}
}
But the lauer is not showing video content if i play same video again , here if the user play same video which is already running it should continue from current duration instead of restarting

Resources