Streaming .m3u8 using MPMoviePlayerController does not work - swift

I used the example in how to play a local video and tried to modify for use on .m3u8 file. I am unable to make it work. I get a blank screen. I confirmed that the file was ok by testing on VLC. Any help would be appreciated.
Here is the code:
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer : MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
playVideo()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func playVideo() {
let path = "http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8"
if let
//path = NSBundle.mainBundle().pathForResource("movie", ofType:"m4v"),
url = NSURL(fileURLWithPath: path),
moviePlayer = MPMoviePlayerController(contentURL: url) {
self.moviePlayer = moviePlayer
moviePlayer.view.frame = self.view.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
self.view.addSubview(moviePlayer.view)
} else {
debugPrintln("Ops, something wrong when playing .m3u8 file")
}
}
}

You've specified your url incorrectly. Change it to this:
url = NSURL(string:path)

Related

Do you need to ask for permission to use the microphone when running an app in simulator?

I Created a simple audio player/recorder player using AVAudioPlayer and AVAudioRecorder. The audio player works as expected but the audio recorder doesn't seem to record or playback the recording even though it builds successfully without any errors. Im wondering if it needs permission to the mic? I'm using version 11.X The code is below any help is much appreciated.
import UIKit
import AVFoundation //must import AVFoundation
class ViewController: UIViewController {
// create property called audioPlayer equal to player
var audioPlayer : AVAudioPlayer?
var audioRecorder : AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//create the audio session
let session = AVAudioSession.sharedInstance()
//set category where we want it to happen (PlayAndRecord) try? = if it doesnt work then set it nil
try? session.setCategory(AVAudioSession.Category.playAndRecord)
//play any audio through device speaker
try? session.overrideOutputAudioPort(.speaker)
// set the session to active, if it doesnt work se it to nil
try? session.setActive(true)
//setup the recording and settings to where audio will be saved (Document folder on device) and set the name and file type (iloveaudio.mp3)
if let basePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let paths = [basePath, "iloveaudioios.mp3"]
if let audioURL = NSURL.fileURL(withPathComponents: paths) {
//create a settings dictionary> orignally it's set to empty using ([:])
var settings : [String : Any] = [:]
//set the file type to mp3
settings[AVFormatIDKey] = Int(kAudioFileMP3Type)
//set the sample rate
settings[AVSampleRateKey] = 44100.0
//set number of channels
settings[AVNumberOfChannelsKey] = 2
// specify the path and settings using var and try to run the recorder if it faile set it to nil
audioRecorder = try? AVAudioRecorder(url: audioURL, settings: settings)
//prepare the recorder of ot fails set it to nil
audioRecorder?.prepareToRecord()
}
}
playerSetup(audioURL: nil)
}
//which file to play if something is recorded
func playerSetup(audioURL:URL?) {
if audioURL == nil {
if let audioPath = Bundle.main.path(forResource: "testaudio", ofType: "mp3") {
let tempAudioURL = URL(fileURLWithPath: audioPath)
audioPlayer = try? AVAudioPlayer(contentsOf: tempAudioURL)
}
} else {
audioPlayer = try? AVAudioPlayer(contentsOf: audioURL!)
}
//check if our audio fille exist? and set it to the proerty audioPath
audioPlayer?.prepareToPlay()
//create audio player, make sure it not nil and if its not the prepare to play, then play
}
#IBAction func PlayPressed(_ sender: Any) {
audioPlayer?.play()
}
#IBAction func Pausedpressed(_ sender: Any) {
audioPlayer?.pause()
}
#IBAction func Stop(_ sender: Any) {
audioPlayer?.stop()
audioPlayer?.currentTime = 0
}
#IBAction func Record(_ sender: Any) {
if let recorder = audioRecorder {
if !recorder.isRecording {
recorder.record()
}
}
}
#IBAction func StopRecord(_ sender: Any) {
if let recorder = audioRecorder {
if recorder.isRecording {
recorder.stop()
playerSetup(audioURL: recorder.url)
}
}
}
}
Yes , You need to add Permission in info.plist
Go to info.plist of your project
Add Privacy - Microphone Usage Description and set it's Value YES(true)
After Setting , when you'll start recording in your app for the first time it will ask for permission , Allow that and you're all set !

Play sound with AKAudioPlayer - iOS

How to declare AKAudioPlayer?
I'm using AudioKit Lib and I just need help to play .wav file with change file button.
import UIKit
import AudioKit
class ViewController: UIViewController {
let file = NSBundle.mainBundle().pathForResource("song", ofType: "wav")
let song = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = song
AudioKit.start()
song.play()
}
#IBAction func btn(sender: AnyObject) {
song.replaceFile("NewFile")
song.play()
}
}
This is a very fast solution to your problem. It can be done better but at least you can get the idea.
First try to make a new class with a function to play your file and then another function to reload your new replacement file like this.
class PlayMyMusic {
var songFile = NSBundle.mainBundle()
var player: AKAudioPlayer!
func play(file: String, type: String) -> AKAudioPlayer {
let song = songFile.pathForResource(file, ofType: type)
player = AKAudioPlayer(song!)
return player
}
func rePlay(file: String, type: String, curPlay: AKAudioPlayer) {
let song = songFile.pathForResource(file, ofType: type)
curPlay.stop()
curPlay.replaceFile(song!)
curPlay.play()
}
}
Initiate the class inside your view
class testViewController: UIViewController {
let doPlay = PlayMyMusic().play("A", type: "wav")
.........
.........
Play your music inside your view
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = self.doPlay
AudioKit.start()
doPlay.looping = true
doPlay.play()
}
Then when you want to reload a new file use the rePlay function
#IBAction func btn(sender: AnyObject) {
PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay)
}
take look on AudioKit playground
update
AKAudioPlayer is deprecated, use AudioPlayer insted and check AudioKit v5 Migration Guide

How to write code to stop multiple audio files swift?

good morning
How to write code to stop multiple audio files in this code
I looked for it and did not find anything useful please help me
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["001" , "002" , "003" , "004" , "005" , "006" , "007" , "008"]
var Audios = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for sound in soundFilenames {
do {
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
Audios.append(audioPlayer)
}catch{
Audios.append(AVAudioPlayer())
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttun001(sender: UIButton) {
let audioplayer = Audios [sender.tag]
audioplayer.play()
}
}
Use a normal loop, check if is playing and stop the ones playing
func stopAudios(){
for audioPLayer in Audios{
if audioPLayer.playing{
audioPLayer.stop()
}
}
}
Also don't forget to prepare your AVAudioPlayer
audioPlayer.prepareToPlay()

Integrate iAd pre-roll video integration in my app?

I want to integrate an iAd Pre-Roll video Ad to my application. When I run this application, it gives me this error:
Domain=ADErrorDomain Code=0 "The operation couldn’t be completed. (ADErrorDomain error 0.)
I want to know if this code is correct or incorrect. Thanks for your help.
import UIKit
import MediaPlayer
import iAd
class ViewController: UIViewController {
var moviePlayer : MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSBundle.mainBundle().URLForResource("intro", withExtension: "mp4")
moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer!.view.frame = view.frame
moviePlayer!.prepareToPlay()
view.addSubview(moviePlayer!.view!)
moviePlayer.playPrerollAdWithCompletionHandler { (error) -> Void in
NSLog("\(error)")
self.moviePlayer.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is one of my modified App Delegate function:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
MPMoviePlayerController.preparePrerollAds()
return true
}
You're trying to display your Pre-Roll Video Ad before your application has had any time to download it. Fire your moviePlayer.playPrerollAdWithCompletionHandler after a few seconds or move the video to a later point in your intro so your application has time to download the ad. Check my example:
import UIKit
import MediaPlayer
import iAd
class ViewController: UIViewController {
// Create our MPMoviePlayerController
var moviePlayer = MPMoviePlayerController()
override func viewDidLoad() {
super.viewDidLoad()
// Preload ad
MPMoviePlayerController.preparePrerollAds()
// Setup our MPMoviePlayerController
moviePlayer.view.frame = self.view.bounds
moviePlayer.setFullscreen(true, animated: true)
}
#IBAction func playVideoButton(sender: AnyObject) {
// Add our MPMoviePlayerController to our view
self.view.addSubview(moviePlayer.view)
// Path of video you want to play
let videoURL = NSBundle.mainBundle().URLForResource("videoName", withExtension:"MOV")
// Set the contents of our MPMoviePlayerController to our video path
moviePlayer.contentURL = videoURL
// Prepare our movie for playback
moviePlayer.prepareToPlay()
// Play our video with a prerolled ad
moviePlayer.playPrerollAdWithCompletionHandler { (error) -> Void in
if (error) != nil {
NSLog("\(error)")
}
self.moviePlayer.play()
}
}
Tapping the UIButton playVideoButton a few seconds after application launch will play the prerolled video advertisement and then the desired video.
Also, If you're testing on your device go to Settings>Developer>Fill Rate> and make sure it is set to 100%.

dismissMoviePlayerViewControllerAnimated not working in Swift

There don't seem to be any SO posts on dismissMoviePlayerViewControllerAnimated in Swift so I guess I'll kick things off.
I have a table cell, when you do a long press on it, it displays a video. When the video ends, my goal is to take the user back to the table view. That last piece is the bit that's not working.
Any help here would be greatly appreciated. I've read through the Apple docs and some posts about this in Objective-C. Seems that the answer is to run dismissMoviePlayerViewControllerAnimated, a method on UIViewController but it's not working.
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer:MPMoviePlayerController!
#IBOutlet weak var longPressView: UIView!
let longPressRec = UILongPressGestureRecognizer()
func longPressedView() {
playVideo()
}
func videoHasFinishedPlaying(notification: NSNotification){
println("Video finished playing")
self.dismissMoviePlayerViewControllerAnimated()
// not returning me to the ViewController
}
func playVideo() {
// get path and url of movie
let path = NSBundle.mainBundle().pathForResource("IMG_8602", ofType:"MOV")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
// construct the views
moviePlayer.view.frame = self.view.bounds
self.view.addSubview(moviePlayer.view)
moviePlayer.fullscreen = true
// remove controls at top and bottom of video
moviePlayer.controlStyle = MPMovieControlStyle.None
// add event observer for videoHasFinsihedPlaying
NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoHasFinishedPlaying:",
name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
longPressRec.addTarget(self, action: "longPressedView")
longPressView.addGestureRecognizer(longPressRec)
longPressView.userInteractionEnabled = true
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your code does not work because you are using MPMoviePlayerController instead of MPMoviePlayerViewController.
You are calling:
self.dismissMoviePlayerViewControllerAnimated()
but there is no MPMoviePlayerViewController to dismiss. That's why nothing happens.
If you prefer to use MPMoviePlayerController (as in the code you posted), after adding manually its view, you also have to manually remove it.