why video is not getting played only showing loader in swift - ios

I am trying to play the video from the web url it showing buffering loader only but not getting played I have used the following code.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url = URL(string: "https://sandbox-api.digiboxx.com/uploads/E2D6024483AB4B04/1602945683_sample_640x360.mp4")!
playVideo(url: url)
}
func playVideo(url: URL) {
let player = AVPlayer(url: url)
let vc = AVPlayerViewController()
vc.player = player
self.present(vc, animated: true) { vc.player?.play() }
}

I tried your URL just in the browser (Safari) on my computer and nothing plays. So I think something is wrong with the URL or the file at the other end.

I tested your link and the video is loading, so I don't know why your code isn't working ...
This is how I use VideoPlayer in Swift :
import UIKit
import AVKit
class MediaManager: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
play(url: "yourUrl")
}
func play (url: String) {
player = AVPlayer(url: URL(string: url)!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.view.present(playerViewController, animated: false) { self.player.play() }
}
}
Try with my code and tell me if it's okay for you

Related

using avplayerkit issue while playing video black screen coming

hello i am new to swift and i am using AVPlayerViewController for plaing video from my url but issue is that i am not able to load video only black screen showing let me show my code
Code
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var viewPlayer: UIView!
var player: AVPlayer!
var avpController = AVPlayerViewController()
var url = "https://www.youtube.com/watch?v=HsQvAnCGxzY"
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: self.url)
player = AVPlayer(url: url!)
avpController.player = player
avpController.view.frame.size.height = viewPlayer.frame.size.height
avpController.view.frame.size.width = viewPlayer.frame.size.width
self.viewPlayer.addSubview(avpController.view)
// Do any additional setup after loading the view, typically from a nib.
}
}
Please refer code given and tell me where i am done wrong so that i can able to play video Thanks In Advance
Actually Its problem of URL .
AVPlayer never supports YouTube video. It supports mp4 format.
If you want to play a video in your ViewController, you have to use AVPlayerLayer. You have to implement player controllers yourself.
override func viewDidLoad() {
super.viewDidLoad()
// creating video url
guard let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else {
return
}
// create AVPlayer
let player = AVPlayer(url: videoURL)
// setup AVPlayerLayer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
// start playing
player.play()
}
Otherwise use AVPlayerViewController. Instead of using its view present the viewController itself.
override func viewDidLoad() {
super.viewDidLoad()
// creating video url
guard let videoURL = URL(string: "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4") else {
return
}
// setup AVPlayer and AVPlayerViewController
let player = AVPlayer(url: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
}
override func viewDidAppear(_ animated: Bool) {
// presenting playerViewController only after the viewControllers view was added to a view hierarchy.
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}

Play Local Video File

I have followed a tutorial and trying to get a video to pop up when I press a button. The video pops up but the actual video does not start playing and I just get this screen....
Blank Screen image
the code is as follows:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var playerController = AVPlayerViewController()
var player:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let videoString:String? = Bundle.main.path(forResource: "motorbikes", ofType: ".m4v")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
}
}
#IBAction func goButton(_ sender: Any) {
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
}
You have forgot to set playercontroller's player instance as phuc-nguyen said
or else you can make use of AVPlayerLayer to play the video without using AVPlayerViewController
let player = AVPlayer(url: URL(string: "path/myvideo.mp4")!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
Using AVPlayerLayer you can customize the player like adding your own controls or views and it won't be a full screen view usually though.
But if you are not looking for any customization its good to stick with AVPlayerViewController it has all the controls baked in
Depends on your requirement

Stop AV Player after done is pressed

I get my local video to load into a new view controller, but after hitting done it disappears and immediately pops back up again. I don't know if there is a way to track the notifications or what.
Here is my code:
import UIKit
import AVKit
import AVFoundation
class VideoController1: UIViewController {
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
playerView = AVPlayer(url: fileURL as URL)
playerViewController.player = playerView
self.present(playerViewController, animated: true){
self.playerViewController.player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You put your code
let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
playerView = AVPlayer(url: fileURL as URL)
playerViewController.player = playerView
self.present(playerViewController, animated: true){
self.playerViewController.player?.play()
}
inside of ViewDidAppear for the ViewController.
ViewDidAppear() occurs when your view is presented on the screen again. So this means, that when the AVPlayer is closed, it goes back to that View, and the AVPlayer will be presented again.
You have 2 options:
Make a UIButton and an Action to that button
var button = UIButton(frame: CGRect(0, self.view.frame.height*0.9, self.view.frame.width, self.view.frame.height*0.1))
button.addTarget(self, #selector(VideoController1.playController), nil)
self.view.addSubview(button)
let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
func playController() {
playerView = AVPlayer(url: fileURL as URL)
playerViewController.player = playerView
self.present(playerViewController, animated: true){
self.playerViewController.player?.play()
}
}
-- OR --
If you want the controller to play only the first time the user sees the view, and that is it, then you can do
var played = false
func viewDidAppear() {
if(!played) {
let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
playerView = AVPlayer(url: fileURL as URL)
playerViewController.player = playerView
self.present(playerViewController, animated: true){
played = true
self.playerViewController.player?.play()
}
}
}
Don't quote me on the code above, just typed it up real quick to give you a general idea.

iPhone simulator plays video, real device won't

I am building an app in Swift on Xcode 7.2
I added a video to my ViewController. Here's the code:
import UIKit
import AVKit
import AVFoundation
class GymViewController: UIViewController {
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
let fileFemaleURL = NSURL(fileURLWithPath:"/Users/marienkoen/Documents/AppDevelopment/ROZsport/ROZsport/GymFemale-2434.m4v")
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playButtonPressed(sender: AnyObject) {
playerView = AVPlayer(URL: fileFemaleURL)
playerViewController.player = playerView
self.presentViewController(playerViewController, animated: true){
self.playerViewController.player?.play()
}
I can play this video when running the app in the simulator, but it will not work on a real device. What am I missing here?
I might be reading this wrong, but you appear to be using a file located on your computer?
Thanks for all the hints. I created these:
let path = NSBundle.mainBundle().pathForResource("video", ofType:"m4v")
And called them in the button action:
#IBAction func playButtonPressed(sender: AnyObject) {
playerView = AVPlayer(URL: NSURL(fileURLWithPath: path!))
playerViewController.player = playerView
self.presentViewController(playerViewController, animated: true){
self.playerViewController.player?.play()}}
And it WORKS!!
Thanks!
Because your path you was using is from simulator, on real device it changed.
if you added this file to your project, you can get this url via:
func getDocumentsURL() -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
return documentsURL
}
func fileInDocumentsDirectory(filename: String) -> String {
let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!
}
Maybe the problem is that filenames are case-sensitive on the iPhone, but not in the simulator?

Remote mp3 file taking a lot of time to play in swift ios

i'm in trouble. i want to play a remote mp3 file in my app. but mp3 file taking a lot of time (approx 5-6 minute) to play. why ?
Anyone can suggest what should i do ?
import UIKit
import AVFoundation
class TestViewController: UIViewController, AVAudioPlayerDelegate {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func play(sender: AnyObject) {
let url = "http://www.example.com/song.mp3"
let fileURL = NSURL(string: url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()))
let soundData = NSData.dataWithContentsOfURL(fileURL, options: nil, error: nil)
var error: NSError?
self.player = AVAudioPlayer(data: soundData, error: &error)
if player == nil
{
if let e = error
{
println(e.localizedDescription)
}
}
player.volume = 1.0
player.delegate = self
player.prepareToPlay()
player.play()
}
}
Thanks in advance.
Use AVPlayer instead of AVAudioPlayer for streaming audio. It can be as simple as this --
let urlString = "http://www.example.com/song.mp3"
let url = NSURL(string: urlString)
var avPlayer = AVPlayer(URL: url)
avPlayer.play()
You can also set an observer on the AVPlayer.status property to manage its changing status. Check out:
https://stackoverflow.com/a/13156942/2484290 (objective c)
And of course the AVPlayer docs are here:
https://developer.apple.com/LIBRARY/ios/documentation/AVFoundation/Reference/AVPlayer_Class/index.html#//apple_ref/occ/cl/AVPlayer
Try using my example where you can work with the cache and the remote file.
player.automaticallyWaitsToMinimizeStalling = false // by default true, so It is important to solve your problem in a mp3 file remotely
This feature is available iOS 10.0+
var player: AVPlayer!
enum AudioType: String {
case remote
case cache
}
#IBAction func remotePressed(_ sender: Any) {
playAudio(type: .remote, fileURL: "http://www.example.com/song.mp3")
}
#IBAction func cachePressed(_ sender: Any) {
if let fileURL = Bundle.main.path(forResource: "jordan", ofType: "mp3") {
playAudio(type: .cache, fileURL: fileURL)
}
}
private func playAudio(type: AudioType, fileURL: String) {
let url = type == .cache ? URL.init(fileURLWithPath: fileURL) : URL.init(string: fileURL)
let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)
player.automaticallyWaitsToMinimizeStalling = false//It's important
player.play()
}
Its may be late.
Yes. what #lemon lime pomelo has said. you should use AVPlayer instead of AVAudioPlayer.
Also you can use MediaPlayer.
import UIKit
import MediaPlayer
#IBAction func playSong(sender: AnyObject) {
print("Song")
self.playAudio("yourAudioURL.mp3")
}
func playAudio(URL:String){
let movieurl:NSURL? = NSURL(string: "\(URL)")
if movieurl != nil {
self.movie = MPMoviePlayerViewController(contentURL: movieurl!)
}
if self.movie != nil {
self.presentViewController(self.movie!, animated: true, completion: nil)
self.movie?.moviePlayer.play()
}
}
It is slow because your program downloads all the song before starting playing

Resources