'AVPlayerViewController audio continues playing in background after dismissal
My goal is to:
- Record a video
- Show it in a view and play it on a loop
- Dismiss it from the view
- Repeat with a new video
Problem:
Steps 1-3 work. However, the audio continues playing in the background after I toggle camera.showMoviePreview to false
Here is the view in which I render the video:
if camera.showMoviePreview {
CustomVideoPlayer(url: camera.previewURL)
}
Here is my AVPlayerViewController
struct CustomVideoPlayer: UIViewControllerRepresentable {
///URL of the video
var url:URL?
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
let playerLooper: AVPlayerLooper!
let url: URL = url!
let player1 = AVPlayer(url: url)
player1.preventsDisplaySleepDuringVideoPlayback = true
player1.allowsExternalPlayback = true
controller.showsPlaybackControls = false
controller.videoGravity = .resizeAspectFill
controller.player = player1
controller.player?.play()
let playerItem = AVPlayerItem(url: url)
let player = AVQueuePlayer(playerItem: playerItem)
playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: controller.player?.currentItem, queue: .main)
{ _ in
controller.player?.seek(to: CMTime.zero)
controller.player?.play()
}
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
}
I believe the audio continues playing because I am not unmounting the AVPlayerViewController, but I'm not sure the proper way to do so
Solution 1:[1]
Simply you can stop video in "onDisapear" method,
1, define AVPlayer property in the class not in the makeUIViewController.
2, define CustomVideoPlayer(url: camera.previewURL) as a view like:
var videoPlayer: some View{
CustomVideoPlayer(url: camera.previewURL)
}
3, use int like:
if camera.showMoviePreview {
videoPlayer
.onDisappear {
camera.videoPlayer.pause()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohsen m |
