Play video from url without extension swift - swift

I want to play video from url returns from service, url doesn't have extension, so it doesn't work. what should I do?
xcode9 swift 4
import AVKit
import AVFoundation
import MediaPlayer
import AudioToolbox
class ViewController: UIViewController {
#IBOutlet weak var player_View: UIView!
let videoURL = URL(string: "http://45.58.42.105:82/Handlers/ImageHandler.ashx?fileReference=67f0dce7-a5f5-4894-a8fd-5996f135626c");
var playerVC = AVPlayerViewController()
var playerView = AVPlayer()
var urlStr = "";
override func viewDidLoad() {
super.viewDidLoad()
self.playVideo();
}
func playVideo() {
self.playerView = AVPlayer(url: videoURL!)
self.playerVC.player = playerView
self.player_View.addSubview(self.playerVC.view)
playerVC.view.frame = self.player_View.frame
playerView.play()
}
}

Related

Problem with get path to a subfolder in main bundle in AVPlayer

I'm improving the code I have for my project.
I stuck with the process of calling videos by subfolders because the code reads all the mp4 files, it finds.
Applying different codes that I have found on the internet, but I end up breaking all the code without success. I would appreciate help or advice in this regard.
Attached image that shows the location of folders with the different videos that I would like to separate my view basic and intermediate folder
import UIKit
import AVKit
import AVFoundation
class BasicLevel: UIViewController, UITableViewDataSource, UITableViewDelegate, AVPlayerViewControllerDelegate{
var videoArray = [String]()
#IBOutlet weak var videoView: UIView!
#IBOutlet weak var videoTableView: UITableView!
var videoVC = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
videoTableView.delegate = self
videoTableView.dataSource = self
videoView.addSubview(videoVC.view)
videoVC.view.frame = videoView.frame
videoVC.showsPlaybackControls = false
let filemanager = FileManager.default
let path = Bundle.main.resourcePath!
let allItems = try? filemanager.contentsOfDirectory(atPath: path)
for singleItem in allItems! {
if singleItem.hasSuffix("mp4") {
videoArray.append(singleItem)
}
}
if videoArray.count > 0 {
playTopVideo(value: 0)
}
}
func playTopVideo(value: Int) {
let nameComponent = videoArray[value].components(separatedBy: ".")
let name = nameComponent[0]
let path = Bundle.main.path(forResource: name, ofType: "mp4")
let url = URL(fileURLWithPath: path!)
videoVC.player = AVPlayer(url: url)
videoVC.player?.play()
}
}
First of all you are responsible for creating the directory structure of the bundle so don't mess it up.
Secondly use the URL related API.
For example put all mp4 files in a subdirectory named videos. It's crucial that you create a real blue folder rather than a group (yellow) folder.
This would reduce your code to
var videoArray = [URL]()
override func viewDidLoad() {
super.viewDidLoad()
videoTableView.delegate = self
videoTableView.dataSource = self
videoView.addSubview(videoVC.view)
videoVC.view.frame = videoView.frame
videoVC.showsPlaybackControls = false
videoArray = Bundle.main.urls(forResourcesWithExtension: "mp4", subdirectory: "videos")!
playTopVideo(value: 0)
}
func playTopVideo(value: Int) {
let videoURL = videoArray[value]
videoVC.player = AVPlayer(url: videoURL)
videoVC.player?.play()
}

tvOS/Swift 3: Why is contentOverlayView not displayed?

I have the following code for a tvOS app. It plays video just as I would like, but the the contentOverlayView I've set does not appear. From examples I've looked at I think it should be working. Can someone please explain what I am doing wrong?
import Foundation
import UIKit
import AVKit
class videoPlayer: AVPlayerViewController {
var thePlayer: AVPlayer?
var movieToPlay: AVPlayerItem?
var movieURL: String?
let theVideoPlayer = AVPlayerViewController()
#IBOutlet weak var videoInfo: UIView!
override func viewDidLoad(){
theVideoPlayer.contentOverlayView?.addSubview(videoInfo)
theVideoPlayer.player = thePlayer
self.view.addSubview(theVideoPlayer.view)
theVideoPlayer.view.frame = self.view.frame
NotificationCenter.default.addObserver(self, selector: #selector(videoPlayer.videoDone), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: thePlayer?.currentItem)
playVideo(movieURL!)
}
func playVideo(_ movieURL: String){
let movieToPlay = AVPlayerItem(url: URL(string: movieURL)!)
thePlayer = AVPlayer(playerItem: movieToPlay)
thePlayer!.play()
}
func videoDone(){
dismiss(animated: true, completion: nil)
}
}
I was confused about some things. Here's what worked:
import Foundation
import UIKit
import AVKit
class videoPlayer: UIViewController {
var movieURL:String = ""
var movieTitle:String = ""
var playerController:AVPlayerViewController?
#IBOutlet weak var videoInfo: UIView!
#IBOutlet var titleLabel: UILabel!
override func viewDidLoad(){
titleLabel.text = movieTitle
playerController = AVPlayerViewController()
playerController?.player = AVPlayer()
self.addChildViewController(playerController!)
self.view.addSubview((playerController?.view)!)
playerController?.didMove(toParentViewController: self)
playerController?.view.frame = self.view.frame
playerController?.contentOverlayView?.addSubview(videoInfo)
let movieToPlay = AVPlayerItem(url: URL(string: movieURL)!)
playerController?.player = AVPlayer(playerItem: movieToPlay)
playerController?.player?.play()
NotificationCenter.default.addObserver(self, selector: #selector(videoDone), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: playerController?.player?.currentItem)
}
func videoDone(){
print("DONE")
dismiss(animated: true, completion: nil)
}
}
The UIView displays just as expected.

How can I play a video using AVPlayer?

Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
I would like to play a video from internet using AVPlayer.
But, a error occurred "super.init(frame: frame)" in AVPlayer.swift of below source list.
Thread 1:EXC_BAD_ACCESS (code=2, address=0x16fc07fe0)
How can I play a video using AVPlayer?
If there is wrong point except point of error, let me know it, too.
AVPlayerView.swift
import Foundation
import UIKit
final class AVPlayerView : UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override public class var layerClass: Swift.AnyClass {
get {
return AVPlayerView.self
}
}
}
ViewController.swift
import UIKit
import AVFoundation
import CoreMedia
class ViewController: UIViewController {
var playerItem : AVPlayerItem!
var videoPlayer : AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
let url:NSURL = NSURL(string: "https://aaa.com/test.m3u8")!
let avAsset = AVURLAsset(url: url as URL, options: nil)
playerItem = AVPlayerItem(asset: avAsset)
videoPlayer = AVPlayer(playerItem: playerItem)
print(self.view.bounds)
let videoPlayerView = AVPlayerView(frame: self.view.bounds)
let layer = videoPlayerView.layer as! AVPlayerLayer
layer.videoGravity = AVLayerVideoGravityResizeAspect
layer.player = videoPlayer
self.view.layer.addSublayer(layer)
videoPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is code to play video:
let videoURL = NSURL(string: "PUT_YOUR_PROPER_URL")
let playerAV = AVPlayer(url: videoURL! as URL)
let playerLayerAV = AVPlayerLayer(player: playerAV)
playerLayerAV.frame = self.view.bounds
self.view.layer.addSublayer(playerLayerAV)
playerAV.play()
AVPlayer support below extension:
public.mpeg
public.mpeg-2-video
public.avi
public.aifc-audio
public.aac-audio
public.mpeg-4
public.au-audio
public.aiff-audio
public.mp2
public.3gpp2
public.ac3-audio
public.mp3
public.mpeg-2-transport-stream
public.3gpp
public.mpeg-4-audio
Make sure you can use supported video in AVPlayer.

Can not play sound Swift

I'm having some trouble playing a sound which is attached to a button/IBAction.
When I do the exact same thing for iOS in Xcode, it works perfectly. However, when I do this for OS X, it doesn't work. Any ideas?
import Cocoa
import AVFoundation
class ViewController: NSViewController, NSSpeechRecognizerDelegate {
var pingAudioPlayer : AVAudioPlayer?
var sr = NSSpeechRecognizer()
#IBOutlet var output: NSTextView?
func playPing(){
let pingSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
pingAudioPlayer = AVAudioPlayer(contentsOfURL: pingSound, error: nil)
pingAudioPlayer!.prepareToPlay()
pingAudioPlayer!.currentTime = 0
pingAudioPlayer!.play()
}
#IBAction func soundTest(sender: AnyObject) {
playPing()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sr.delegate = self
sr.commands = ["Ping", "Ping Mac"]
sr.startListening()
}
func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
output!.string! += "\(command)\n"
playPing()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
The main problem was the speechRecognizer method, it wasn't the right signature.
import AVFoundation
class ViewController: NSViewController, NSSpeechRecognizerDelegate {
var pingAudioPlayer : AVAudioPlayer?
var sr = NSSpeechRecognizer()
#IBOutlet var output: NSTextView?
func playPing(){
let pingSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
pingAudioPlayer = try? AVAudioPlayer(contentsOfURL: pingSound)
pingAudioPlayer?.prepareToPlay()
pingAudioPlayer?.currentTime = 0
pingAudioPlayer?.play()
}
#IBAction func soundTest(sender: AnyObject) {
playPing()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sr?.delegate = self
sr?.commands = ["Ping", "Ping Mac"]
sr?.startListening()
}
func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: String) {
output?.string! += "\(command)\n"
playPing()
}
}

Trigger sound play() with NSSpeechRecognizer Swift

I'm trying to trigger a sound after I say a word. The speech recognizer recognizes the word when I say it and I've set it up so it puts out a string each time I say the command. What I'd like to do is trigger a sound after I say that specific word. This is what I have so far.
import Cocoa
import AVFoundation
class ViewController: NSViewController, NSSpeechRecognizerDelegate {
var ping = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
var pingAudioPlayer = AVAudioPlayer()
var sr = NSSpeechRecognizer()
#IBOutlet var output: NSTextView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
pingAudioPlayer = AVAudioPlayer(contentsOfURL: ping, error: nil)
sr.delegate = self
sr.commands = ["Ping", "Ping Mac"]
sr.startListening()
}
func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
output!.string! += "\(command)\n"
pingAudioPlayer.play()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
UPDATE:
import Cocoa
import AVFoundation
class ViewController: NSViewController, NSSpeechRecognizerDelegate {
var ping = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
let pingAudioPlayer = AVAudioPlayer()
var sr = NSSpeechRecognizer()
#IBOutlet var output: NSTextView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sr.delegate = self
sr.commands = ["Ping", "Ping Mac"]
sr.startListening()
}
func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
output!.string! += "\(command)\n"
var pingAudioPlayer = AVAudioPlayer(contentsOfURL: ping, error: nil)
pingAudioPlayer.prepareToPlay()
pingAudioPlayer.play()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Not sure why the audio player is not playing the sound once the word is recognized. Any ideas?
You aren't telling the audio player which sound to play. Try this:
func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
do{
let pingAudioPlayer = try AVAudioPlayer(contentsOfURL:ping)
pingAudioPlayer.prepareToPlay()
pingAudioPlayer.play()
}catch {
print("Error getting the audio file")
}
}