My code perfectly works fine in the simulator and it streams the url without any issue. But when plugged to the actual device it doesnt play the audio. My code as bellow
var playerItem: AVPlayerItem?
var player: AVPlayer?
func initPlayer() {
let url:URL = URL(string:"https://storage.googleapis.com/purelightdatabucket/samples%2F60-Energy%20UPLIFT.mp3")!
self.playerItem = AVPlayerItem(url: url)
self.player=AVPlayer(playerItem: self.playerItem!)
let playerLayer=AVPlayerLayer(player: self.player!)
playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
self.view.layer.addSublayer(playerLayer)
}
Put this code in didFinishLaunchingWithOptions
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
you can use this too :
You need to add AVKit & AVFoundation to your frameworks path and import them :
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let playerItem = AVPlayerItem(url: URL(string: "https://storage.googleapis.com/purelightdatabucket/samples%2F60-Energy%20UPLIFT.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Related
I am trying to get a .m3u8 video stream to play within my app. I am programming in Swift for iOS 9 and 10.
Here is what I got so far:
import UIKit
import AVKit
import AVFoundation
import DynamicBlurView
class VideoPlayerViewController: AVPlayerViewController {
var urlString: String!
let blurView = DynamicBlurView()
override func viewDidLoad() {
super.viewDidLoad()
streamVideo()
}
func streamVideo() {
blurView.frame = view.frame
UIView.showProgressView(on: view, blurView: blurView)
let url = URL(string: urlString!)
let item = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: item)
UIView.hideProgressView(on: view, blurView: blurView)
player?.play()
}
}
This should be simple, but I am getting errors and crashes all over the place.
This is the error I am getting:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo={NSLocalizedDescription=The operation could
not be completed, NSUnderlyingError=0x7b5b6810 {Error
Domain=NSOSStatusErrorDomain Code=-12782 "(null)"},
NSLocalizedFailureReason=An unknown error occurred (-12782)}
Please help me!
EDIT:
Tried this suggestion with no luck. the app still crashes. The crash brings me to the AppDelegate if that info helps anyone.
import UIKit
import AVKit
import AVFoundation
import DynamicBlurView
class VideoPlayerViewController: AVPlayerViewController {
var urlString: String!
let blurView = DynamicBlurView()
override func viewDidLoad() {
super.viewDidLoad()
streamVideo()
}
func streamVideo() {
blurView.frame = view.frame
UIView.showProgressView(on: view, blurView: blurView)
let sampleURL = "https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8"
guard let url = URL(string: sampleURL) else { return }
let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player?.play()
UIView.hideProgressView(on: view, blurView: blurView)
}
}
You should make sure your URL provides a valid HLS source.
import UIKit
import AVKit
import AVFoundation
class myAVPlayerViewController: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
// custom HLS
// http://localhost:3000/assets/videos/iframe_index.m3u8
// apple HLS example
// https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8
guard let url = URL(string: "https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8") else { return }
let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player?.play()
}
}
Also, remember to set the NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your Info.plist.
I'm having issues with playing back a video. All I want is for the video to playback after the launch image has been displayed. I followed this (https://www.youtube.com/watch?v=iYATp9--VIM) tutorial but when I simulated I received a blank screen.
Here is the code:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupView() {
let path = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("streetview", ofType: "mov")!)
let player = AVPlayer(URL:path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.frame
self.videoView.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
player.play()
}
}
Please help me if you can!
If you're just getting a blank black screen, it would generally point to an issue with the source of the video. I'd check that you're spelling the name of your file correctly and that it definitely is a .mov file.
I use this code to launch the AVPlayer and play my video. It plays a video from a URL from the internet. I have it inside my button function so it happens when the user presses the play button I have:
let videoURL = NSURL(string: "YOUR URL") {
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
I can confirm this works for me in Swift 2.0
I've got some problems with video on my app's background.
Here is my program code:
import UIKit
import AVKit
import AVFoundation
class IntroViewController: UIViewController {
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("intro", withExtension: "mov")!
player = AVPlayer(URL: videoURL)
player?.actionAtItemEnd = .None
player?.muted = false
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
player?.play()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "loopVideo",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: nil)
}
func loopVideo() {
player?.seekToTime(kCMTimeZero)
player?.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
After launching my program, the Music app is muted. How do I fix it?
And one more question: after returning to this screen from home screen, without closing the app, video stops. Where is the problem?
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.
I'm trying to play a video from a server using Swift.
I have imported MediaPlayer framework, here is my code:
import UIKit
import MediaPlayer
class VideoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
var moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)
self.view.addSubview(moviePlayer.view)
moviePlayer.fullscreen = true
moviePlayer.controlStyle = MPMovieControlStyle.Embedded
}
}
I only get a black box when I run in the simulator but no video is playing no matter where I try to load a video from.
UPDATE
Here is the current code
var url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
var moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)
moviePlayer.movieSourceType = MPMovieSourceType.File
self.view.addSubview(moviePlayer.view)
moviePlayer.prepareToPlay()
moviePlayer.play()
This code interestingly plays ~2 seconds of video before going black again!
UPDATE 2019, Swift 4:
MPMovieControlStyle' was deprecated in iOS 9.0: Use AVPlayerViewController in AVKit.
So, following the advice, let's change it. Original answer from 2016 is below.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.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() }
}
}
The original answer:
import UIKit
import MediaPlayer
class VideoViewController: UIViewController {
var moviePlayer:MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
let url:NSURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer.view.frame = CGRect(x: 20, y: 100, width: 200, height: 150)
self.view.addSubview(moviePlayer.view)
moviePlayer.fullscreen = true
moviePlayer.controlStyle = MPMovieControlStyle.Embedded
}
}
import AVKit
import AVFoundation
class VideoController: UIViewController
override func viewDidLoad()
{
let videoURL = NSURL(string: "VideoUr")
let player = AVPlayer(url: videoURL! as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
Import the libraries:
import AVKit
import AVFoundation
import MediaPlayer
import AudioToolbox
Set delegaete like this
AVPlayerViewControllerDelegate
Wrtie pretty code where you want to play like button action:
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playervc = AVPlayerViewController()
playervc.delegate = self
playervc.player = player
self.present(playervc, animated: true) {
playervc.player!.play()
}
100% working and test
I just was having the same issues..
MPMoviePlayerController Stops Playing After 5 seconds - Swift
The issue is your var moviePlayer is going out of scope. By declaring it outside of viewDidLoad like #Victor-Sigler did above, you prevent the black screen issue from happening.