iPhone simulator plays video, real device won't - ios

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?

Related

How to play audio in simulator?

import UIKit
import SwiftUI
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
}
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
let player = AVPlayer.init(url: url!)
player.play()
print(url!)
}
}
file:///Users/user/Library/Developer/CoreSimulator/Devices/C3333006-1A90-4B12-A9F6-E04B3603334C/data/Containers/Bundle/Application/265FB456-9524-44DY-B669-D67ACB7F444C/Xylophone.app/D.wav
I'm trying to play sound, which are already in the package folder, but failed to do so in simulator, can't play any sound even if unmute and increase sound volume of the simulator and my Mac.
I use this code and it works:
let jingleURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "jingle", ofType: ".mp3")!)
let jingleAVPlayer = AVPlayer.init(url: jingleURL)
jingleAVPlayer.play()
The filename is jingle.mp3 and is added in Xcode.
I hope this helps you out ;)

why video is not getting played only showing loader in swift

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

Adding Local files to projects files

import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
#IBAction func playMusic(sender: AnyObject) {
let fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/32134.mp4")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
When I use the app it does not work because the file is on my mac. Please Can someone explain how I put the video file in the project. Thanks
You just need to drag and drop the file like video or image that you want to use in your project statically. Following i just add :
#IBAction func playMusic(sender: AnyObject) {
let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
let fileURL = NSURL(fileURLWithPath: path)
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
Another way is Past your video, audio or image file in your project folder like following:
after that Add this file in to your xcode project by following step:
You get drapDown window and select your file as following:
And you the same code for getting file path:
let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
let fileURL = NSURL(fileURLWithPath: path)
Try checking for the nil. Also get the video file URL from NSBundle
if let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4") {
let fileURL = NSURL(fileURLWithPath: path!)
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}

Implementing video view in the Storyboard

I want to build simple video app thats views a video form youtube links thats users add.
I didn't find "VideoView" I mean If image view is for image what is UIView for videos.
There is no object in the original library that performs video viewing function. But you can import the MediaPlayer framework in your project and add it programmatically.
Here is a Swift example
import MediaPlayer
class Step1ViewController: UIViewController {
var moviePlayer: MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
playVideo()
}
func playVideo() {
let videoView = UIView(frame: CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.width, self.view.bounds.height))
let pathToEx1 = NSBundle.mainBundle().pathForResource("myVideoFile", ofType: "mp4")
let pathURL = NSURL.fileURLWithPath(pathToEx1!)
moviePlayer = MPMoviePlayerController(contentURL: pathURL)
if let player = moviePlayer {
player.view.frame = videoView.bounds
player.prepareToPlay()
player.scalingMode = .AspectFill
videoView.addSubview(player.view)
}
self.view.addSubview(videoView)
}
}
As for further customisations and app notifications it has a bunch of in-build possibilities. So check it out.
To play video apple has provided MPMovieViewController
see this https://developer.apple.com/library/prerelease/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/index.html
and this
http://www.brianjcoleman.com/tutorial-play-video-swift/
In youtube Video case we got embedded links are used so for that you will get help from this https://github.com/gilesvangruisen/Swift-YouTube-Player
import AVFoundation
import AVKit
class ViewController: UIViewController {
var player = AVPlayer()
var playerController = AVPlayerViewController()
func playVideo() {
let videoURL = NSURL(string: videoUrl)
player = AVPlayer(url: videoURL! as URL)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
// Add your view Frame
playerController.view.frame = self.view.frame
// Add subview in your view
self.view.addSubview(playerController.view)
player.play()
}
func stopVideo() {
player.pause()
}
}
In Xcode 10 (with a bit less code):
In the interface builder (Storyboard), add "AVKit Player View Controller"
Create a View Controller that derives from AVPlayerViewController:
import UIKit
import AVKit
class VideoPlayerViewController: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")!
self.player = AVPlayer(url: videoURL)
}
override func viewDidAppear(_ animated: Bool) {
self.player?.play()
}
}
Don't forget to connect this custom class in the storyboard's identity inspector :)
Note: this example uses video URL pointing to a bundle's resource.

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