Live stream using AVPlayer not playing in iOS 11 - swift

I am trying to stream a music from remote url. I am trying to run this in iOS 11 but it not play the music.
ViewController
var session = AVAudioSession.sharedInstance()
var LQPlayer: AVPlayer?
let LOW_URL = URL(string: "http://someLInk.pls")! // not an original url provided at this time.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.avPlayerSetup()
}
func avPlayerSetup() {
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
try session.overrideOutputAudioPort(.none)
try session.setActive(true)
} catch {
print("AVPlayer setup error \(error.localizedDescription)")
}
}
func initPlayer() {
LQPlayer = AVPlayer(url: LOW_URL)
print("player allocated")
}
func deAllocPlayer() {
LQPlayer = nil
print("player deallocated")
}
#IBAction func playBtn(_ sender: Any) {
initPlayer()
LQPlayer?.play()
}
#IBAction func pauseBtn(_ sender: Any) {
LQPlayer?.pause()
deAllocPlayer()
}
}
I set Allow Arbitrary Loads YES in info.plist.
Above code the URL I given is dummy. Actual url is working fine.

Working Code with Live Video Stream
#IBOutlet weak var player_View: UIView!
var LQPlayer: AVPlayer?
let LOW_URL = URL(string:"http://www.streambox.fr/playlists/test_001/stream.m3u8")!
override func viewDidLoad() {
super.viewDidLoad()
self.avPlayerSetup()
LQPlayer = AVPlayer.init(url: LOW_URL)
let avPlayerView = AVPlayerViewController()
avPlayerView.view.frame = self.player_View.bounds
avPlayerView.player = LQPlayer
self.player_View.addSubview(avPlayerView.view)
}
func avPlayerSetup() {
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
try audioSession.setActive(true)
} catch {
print("AVPlayer setup error \(error.localizedDescription)")
}
}
func initPlayer() {
LQPlayer = AVPlayer(url:LOW_URL)
print("player allocated")
}
func deAllocPlayer() {
LQPlayer = nil
print("player deallocated")
}
#IBAction func playBtn(_ sender: Any) {
// initPlayer()
LQPlayer?.play()
}
#IBAction func pauseBtn(_ sender: Any) {
LQPlayer?.pause()
deAllocPlayer()
}

Related

ORSSerialPort with Arduino

I've been trying for a long time to program an Xcode interface to communicate with my Arduino Mega. but the whole thing didn't work as well as intended. I did the whole thing with ORSSerialPort.
In the Xcode project I wrote this for the swift file ViewController.swift :
import Cocoa
import ORSSerial
class ViewController: NSViewController, ORSSerialPortDelegate {
var serialPort = ORSSerialPort(path: "/dev/cu.usbmodem142101")
func SendString(data: String){
let stringData = Data(data.utf8)
serialPort?.send(stringData)
}
func openPort(){
serialPort?.baudRate=9600
serialPort?.delegate=self
serialPort?.parity = .none
serialPort?.numberOfStopBits = 1
serialPort?.open()
print("serialport is open")
}
func closePort(){
serialPort?.delegate=nil
serialPort?.close()
print("serialport is close")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
}
}
#IBAction func onButton(_ sender: Any) {
openPort()
}
#IBAction func OffButton(_ sender: Any) {
closePort()
}
#IBAction func SendButton(_ sender: Any) {
SendString(data: "stringdata blablabla")
}
func serialPortWasOpened(_ serialPort: ORSSerialPort) {
print("serialPort to \(serialPort) is run")
}
func serialPortWasRemovedFromSystem(_ serialPort: ORSSerialPort) {
self.serialPort = nil
}
}
and this code i have load on the Arduino mega:
String angel;
void setup() {
Serial.begin(9600);
}
void loop() {
angel = Serial.readString();
Serial.println(angel);
delay(350);
}
unfortunately it doesn't work and I don't know why.
Your question doesn't provide any detail about what part(s) don't work, but there's one definite problem.
Your Arduino program looks like it echos everything it receives on the serial port back on the same port. In order to see that on the computer, you'll have to implement the serialPort(_:didReceive:) method in your view controller. Something like this:
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
guard let string = String(data: data, encoding: .ascii) else { return; }
print("Received: \(string)")
}

didInititate method for Spotify IOS SDK is not calling even though called sessionManager.initiateSession()

I'm going through Spotify's authentication process and am requesting the scopes appRemoteControl for my app to control music and userReadCurrentlyPlaying for current song. I set up everything from the SPTConfiguration, SPTSessionManager, and SPTAppRemote, and their required delegate methods (SPTAppRemoteDelegate, SPTSessionManagerDelegate, SPTAppRemotePlayerStateDelegate) as well as initiating a session with the requested scopes whenever the user presses a button but I can't get the method
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
to trigger. The authentication process fully works as it goes into my spotify app and returns back to my application and plays a song from the configuration.playURI = "" , however, the method above never is called. I followed the spotify demo project but still does not work. Here is my full code
class LogInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let spotifyClientID = Constants.clientID
let spotifyRedirectURL = Constants.redirectURI
let tokenSwap = "https://***********.glitch.me/api/token"
let refresh = "https://***********.glitch.me/api/refresh_token"
lazy var configuration: SPTConfiguration = {
let configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: URL(string: "Lyrically://callback")!)
return configuration
}()
lazy var sessionManager: SPTSessionManager = {
let manager = SPTSessionManager(configuration: configuration, delegate: self)
if let tokenSwapURL = URL(string: tokenSwap), let tokenRefreshURL = URL(string: refresh) {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
#IBAction func logIn(_ sender: UIButton) {
let requestedScopes: SPTScope = [.appRemoteControl, .userReadCurrentlyPlaying]
sessionManager.initiateSession(with: requestedScopes, options: .default)
}
}
extension LogInViewController: SPTAppRemotePlayerStateDelegate {
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("state changed")
}
}
extension LogInViewController: SPTAppRemoteDelegate {
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
if let error = error {
print("Error subscribing to player state:" + error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
}
extension LogInViewController: SPTSessionManagerDelegate {
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print("failed",error)
}
}
Figured it out. Had to get a hold of the sessionManager from the LogInViewController by making an instance of it
lazy var logInVC = LogInViewController()
then added this line of code into the openURLContexts method in scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
print("Opened url")
guard let url = URLContexts.first?.url else {
return
}
logInVC.sessionManager.application(UIApplication.shared, open: url, options: [:])
}

How to reconnect AKPlayer and AKMixer after AudioKit.stop()

After calling AudioKit.stop(), and then subsequently calling AudioKit.start(), I'm unable to reconnect my AKMixer/AKPlayer to AudioKit. It appears that the engine starts successfully but no sound is produced when I call player.play(). I'm not quite sure what I'm missing. I've boiled it all down to a simple demo project and I've included the most important sections of code below.
View controller
class ViewController: UIViewController {
public let tickSound = MySound(url: "tick.wav")
#IBAction func stopAudioKit(_ sender: Any) {
try! AudioKit.stop()
print("AudioKit stopped")
}
#IBAction func playSound(_ sender: Any) {
tickSound.play()
}
}
Sound Object
class MySound: NSObject {
private static var mixer: AKMixer = AKMixer()
private var player: AKPlayer?
init(url: String) {
super.init()
if let file = try? AKAudioFile(readFileName: url) {
self.player = AKPlayer(audioFile: file)
self.player?.buffering = .always
MySound.mixer.connect(input: self.player)
}
}
func play() {
if AudioKit.output !== MySound.mixer {
AudioKit.output = MySound.mixer
}
if !AudioKit.engine.isRunning {
do {
try AudioKit.start()
} catch {
assert(false)
}
}
if AudioKit.engine.isRunning {
player?.play()
} else {
assert(false)
}
}
}
Github demo project: https://github.com/rednebmas/AudioKitDemo
Thank you!

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()
}
}

Swift: AudioPlayerDidFinished will not be called

My AudioPlayerDidFinishPlaying will not be called after audio has finished. I know it has something to do with my delegate, but I can't fix it on my own.
Can somebody give me some tips? I Googled a lot and I found other questions here with the same issue but it didn't work for me.
Thanks
import UIKit
import Parse
import AVFoundation
class ViewControllerMies: UIViewController, AVAudioPlayerDelegate {
var timer = NSTimer()
var player: AVAudioPlayer = AVAudioPlayer()
var currentStateAudio = ""
var oldAudio = String()
func startTimer() {
if player.playing == false {
print("Tijd voor de Spice Girls")
}
let query = PFQuery(className:"CurrentState")
query.getObjectInBackgroundWithId("9r61TRaRqu") {
(objects: PFObject?, error: NSError?) -> Void in
if error == nil && objects != nil {
self.currentStateAudio = objects!.objectForKey("currentState") as! String
print(self.currentStateAudio)
} else {
print(error)
}
}
if (oldAudio != self.currentStateAudio)
{
let audioPath = NSBundle.mainBundle().pathForResource(self.currentStateAudio, ofType: "mp3")!
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
} catch {
// Process error here
}
player.play()
oldAudio = self.currentStateAudio
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("startTimer"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool)
{
print("Finished Playing")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
you're not setting yourself as the player's delegate
before calling play() do player.delegate = self
if you are using private delegate then its will not call too use this for resolving this issue
//MARK:- This is correct delegate working fine (use this)
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
audioRecorder = nil
}
//MARK:- Insted of this (this will not call)
private func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
audioRecorder = nil
}