FYI, I am using this Github Player: https://github.com/piemonte/Player
I am trying to play a video, but it wont work. On the View Controller's UIView i use background color blue, and when I run this project, I only see a bue background without a player. This is my code:
import UIKit
import Player
import AVFoundation
class ViewController: UIViewController, PlayerDelegate {
#IBOutlet var myView: UIView!
private var player: Player!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fileUrl = NSURL(string: "https://parseapi.back4app.com/files/SAQY2fBCiob9UMqITqAEMo7UxNsU6MCCUURf53Ee/d349a0bdd0962cb0f570c95621aee6df_video.mp4")
self.player = Player()
self.player.delegate = self
player.view.frame.size.width = UIScreen.mainScreen().bounds.size.width
player.view.frame.size.height = player.view.frame.size.width
player.fillMode = AVLayerVideoGravityResizeAspectFill
player.view.sizeToFit()
myView.addSubview(player.view)
let videoUrl: NSURL = fileUrl!
self.player.setUrl(videoUrl)
self.player.playFromBeginning()
self.player.playbackLoops = true
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGestureRecognizer:")
tapGestureRecognizer.numberOfTapsRequired = 1
self.player.view.addGestureRecognizer(tapGestureRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: PlayerDelegate Start
func handleTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) {
switch (self.player.playbackState.rawValue) {
case PlaybackState.Stopped.rawValue:
self.player.playFromBeginning()
case PlaybackState.Paused.rawValue:
self.player.playFromCurrentTime()
case PlaybackState.Playing.rawValue:
self.player.pause()
case PlaybackState.Failed.rawValue:
self.player.pause()
default:
self.player.pause()
}
}
func playerReady(player: Player) {
}
func playerPlaybackStateDidChange(player: Player) {
}
func playerBufferingStateDidChange(player: Player) {
}
func playerPlaybackWillStartFromBeginning(player: Player) {
}
func playerPlaybackDidEnd(player: Player) {
}
/* override func awakeFromNib() {
self.collectionView.autoresizesSubviews = true
self.collectionView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.collectionView.translatesAutoresizingMaskIntoConstraints = true
}*/
// MARK: PlayerDelegate Stop
}
Attempt nr 2:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fileUrl = NSURL(string: "https://parseapi.back4app.com/files/SAQY2fBCiob9UMqITqAEMo7UxNsU6MCCUURf53Ee/d349a0bdd0962cb0f570c95621aee6df_video.mp4")
self.player = Player()
self.player.delegate = self
self.player.view.frame = self.view.bounds
self.addChildViewController(self.player)
self.view.addSubview(self.player.view)
self.player.didMoveToParentViewController(self)
let videoUrl: NSURL = fileUrl!
self.player.setUrl(videoUrl)
self.player.playFromBeginning()
self.player.playbackLoops = true
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGestureRecognizer:")
tapGestureRecognizer.numberOfTapsRequired = 1
self.player.view.addGestureRecognizer(tapGestureRecognizer)
}
When I try to open the link in Safari, it doesn't work, but in Chrome it works fine.. Any suggestions what might be wrong?
Actually the player is not actually added to your view yet.
Please follow this to add this on your view as a sub-viewcontroller.
self.player = Player()
self.player.delegate = self
self.player.view.frame = self.view.bounds
self.addChildViewController(self.player)
self.view.addSubview(self.player.view)
self.player.didMoveToParentViewController(self)
Related
I have an WKWebView there I show my site and I play a sound effect with js but when I do so the background music is stop playing. I like to mix in this sound effect with background music like Spotify.
Any idea how I do so?
This is my code in ViewController.swift
import WebKit
import AVFoundation
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
// Set so play inline works
let webConfiguration = WKWebViewConfiguration()
webConfiguration.allowsInlineMediaPlayback = true
if #available(iOS 10.0, *) {
webConfiguration.mediaTypesRequiringUserActionForPlayback = []
} else {
// Fallback on earlier versions
webConfiguration.mediaPlaybackRequiresUserAction = false
}
webView = WKWebView(frame: CGRect.zero, configuration: webConfiguration)
//super.init(coder: aDecoder)
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Set so we can play sound effect without stop background music
// Get the local lang from iphone
var locale = Locale.preferredLanguages[0]
if (locale.contains("-")) {
locale = locale.substring(to: locale.characters.index(locale.startIndex, offsetBy: 2))
}
let url = URL(string: "https://test.com/?lang=" + locale)!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
// add background color to wkwebview to transparent
webView.backgroundColor = UIColor.clear
webView.scrollView.backgroundColor = UIColor.clear
// Change the statusbar to vit
UIApplication.shared.statusBarStyle = .lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have found out that this is not possible.
So I have a video playing in the background and two button images that fade in. Both work fine, however on the simulator when I launch the app, I see the button images on the white screen then it goes into playing the video and the animation. I also have the alpha set to 0 in the main story board on each image. Not sure if this is a simulator/launch screen glitch or my code. My code is below and any help is appreciated. Thanks!
import UIKit
import Parse
import MediaPlayer
class ViewController: UIViewController {
#IBOutlet var loginAlpha: UIButton!
#IBOutlet var signupAlpha: UIButton!
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// code for background video
let theURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp4")
avPlayer = AVPlayer(URL: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.None
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = UIColor.clearColor();
view.layer.insertSublayer(avPlayerLayer, atIndex: 0)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "playerItemDidReachEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: avPlayer.currentItem)
}
func playerItemDidReachEnd(notification: NSNotification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seekToTime(kCMTimeZero)
}
override func viewDidAppear(animated: Bool) {
signupAlpha.alpha = 0
loginAlpha.alpha = 0
UIView.animateWithDuration(1.5, delay: 1.0, options: [], animations: { () -> Void in
self.signupAlpha.alpha = 1.0
self.loginAlpha.alpha = 1.0
}, completion: nil)
avPlayer.play()
paused = false
}
override func viewDidDisappear(animated: Bool) {
avPlayer.pause()
paused = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I found a simple solution for this:
on viewDidLoad ( You can set this on storyboard too. )
loginAlpha.hidden = true
signupAlpha.hidden = true
and on viewDidAppear
signupAlpha.alpha = 0
loginAlpha.alpha = 0
loginAlpha.hidden = false
signupAlpha.hidden = false
i want create a login page for my app, in this case i want to use a video for background of login page, like vine,spotify,uber,...
i play video without problem and add some button and lable in storyboard to my view controllerŲ after run app i can not see objects of view controller
i just see video and objects hide behind of video background how can fix this problem,,,
thanks for helping
this is my code for playing video,,,
lazy var playerLayer:AVPlayerLayer = {
let player = AVPlayer(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BWWalkthrough", ofType: "mp4")!))
player.muted = true
player.allowsExternalPlayback = false
player.appliesMediaSelectionCriteriaAutomatically = false
var error:NSError?
// This is needed so it would not cut off users audio (if listening to music etc.
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch var error1 as NSError {
error = error1
} catch {
fatalError()
}
if error != nil {
print(error)
}
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
playerLayer.videoGravity = "AVLayerVideoGravityResizeAspectFill"
playerLayer.backgroundColor = UIColor.blackColor().CGColor
player.play()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"playerDidReachEnd", name:AVPlayerItemDidPlayToEndTimeNotification, object:nil)
return playerLayer
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.layer.addSublayer(self.playerLayer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
playerLayer.frame = self.view.frame
}
func playerDidReachEnd(){
self.playerLayer.player!.seekToTime(kCMTimeZero)
self.playerLayer.player!.play()
}
You need to add your playerLayer below all the views created when your storyboard loads. Replacing
self.view.layer.addSublayer(self.playerLayer)
with
self.view.layer.insertSublayer(self.playerLayer, atIndex:0)
should do the job, unless there are any subviews of the view controller view that you actually want to be behind the video layer.
Yep, this is my code:
import Foundation
class FbVideoPostDetailedViewController: FbDetailedPostViewController {
var mc = MPMoviePlayerController()
override func viewDidLoad() {
super.viewDidLoad()
let movieURL = NSURL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
self.mc = MPMoviePlayerController.init(contentURL: movieURL)
self.mc.allowsAirPlay = false
self.mc.shouldAutoplay = true
self.mc.view.frame = UIScreen.mainScreen().bounds
self.mc.controlStyle = MPMovieControlStyle.Embedded
self.view.addSubview(self.mc.view)
self.mc.fullscreen = true
self.mc.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I'm just trying to open video in fullscreen mode. Please guide me in right way because FbVideoPostDetailedViewController appears only as a blank screen and video wasn't play.
I have few outlets in FbDetailedPostViewController but I want even to start play in fullscreen at this point.
Please see below code. I am trying to remove the video subview from view when the 'done' button is pressed or video stops playing. I show no errors in the code but the removeFromSubview method does not seem to be working. I am not sure if my syntax is wrong or if it is something to do with having the movieplayer code within the IBAction method and the moviePlayBackDidFinish outside below the viewDidLoad. Any advise much appreciated. Thanks
import Foundation
import UIKit
import MediaPlayer
class VideoViewController: UIViewController {
var moviePlayer:MPMoviePlayerController!
#IBAction func videoLaunch(sender: AnyObject) {
playVideo()
}
func playVideo() {
let path = NSBundle.mainBundle().pathForResource("MyVideo", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer {
player.view.frame = self.view.bounds
moviePlayer?.controlStyle = MPMovieControlStyle.Fullscreen
player.prepareToPlay()
self.view.addSubview(player.view)
}
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "moviePlayBackDidFinish:",
name: MPMoviePlayerPlaybackDidFinishNotification,
object: moviePlayer)
func moviePlayBackDidFinish(notification: NSNotification){
self.view.removeFromSuperview()
}
}
}
You are trying to remove self.view not moviePlayer.view.
Change your moviePlayBackDidFinish code to:
func moviePlayBackDidFinish(notification: NSNotification)
{
if let player = moviePlayer
{
player.view.removeFromSuperview()
}
}