I am wondering how do I hide the view of the AVPlayer.
guard let url = URL(string: "http://stream.radiomedia.com.au:8006/stream.m3u") else {
return
}
// Create a new AVPlayer and associate it with the player view
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
What I want to hide is the black screen it shows as this is just audio. No visual.
So I want to hide the viewer not necessarily the controlls.
You can use AVPlayer
without AVPlayerViewController
if you don't need the UI.
You don't need AVPlayerViewController
to play an audio. You can create a view controller of your own and use AVPlayer
with AVPlayerLayer
.
let player: AVPlayer = AVPlayer()
let playerLayer = AVPlayerLayer(player: self.player)
YOUR_VIEW.layer.addSublayer(self.playerLayer)
// Play the audio
let audioURL = URL(string: url)
let playerItem = AVPlayerItem(url: audioURL)
player.replaceCurrentItem(with: playerItem)
player.play()
You can hide YOUR_VIEW
view if you'd like or display it if you are to play a video. It'd be better if player
has a strong reference so I'd recommend storing it in a class variable. Also call player.play()
on AVPlayer.Status.readyToPlay
event of AVPlayer
. You can learn more onApple's documentation
You can update the background color of the player
let controller = AVPlayerViewController()
controller.contentOverlayView.backgroundColor = UIColor.white
In case you don't want the UI like that of AVPlayerViewController
, you can simply use AVPlayerLayer
and add it as a view's
sublayer
.
guard let url = URL(string: "http://stream.radiomedia.com.au:8006/stream.m3u") else {
return
}
let player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = view.bounds
playerLayer.videoGravity = .resizeAspect
playerLayer.contentsGravity = .resizeAspect
view.layer.insertSublayer(playerLayer, at: 0)
player.play()
AVPlayerLayer
will play the video same as AVPlayerViewController
.
Also, you can add the playerLayer
to any view's layer. Be it main view or any custom view.
For more you can refer the link - https://medium.com/free-code-camp/how-to-set-up-video-streaming-in-your-app-with-avplayer-7dc21bb82f3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.