Streaming audio from a network live stream location - swift

I am trying to play a network audio live stream from our radio station. I followed a tutorial and managed to get it to work, but it plays as if it's a video. I would like to make my own controls (e.g., the user pushes play and a pause button) instead of it opening up a whole new view as if it's a video.
https://i.ibb.co/2PhyYkt/IMG-3189.png
https://i.ibb.co/9T3QbYp/IMG-3190.png
import UIKit
import AVFoundation
import AVKit
var streamController = AVPlayerViewController()
var streamPlayer: AVPlayer?
let streamVideoURL: NSURL? = NSURL(string: "http://dvstream2.bgsu.edu:8000/wbgu")
streamPlayer = AVPlayer(url: streamVideoURL! as URL)
streamController.player = streamPlayer
#IBAction func playBtnTapped(_ sender: Any) {
self.present(self.streamController, animated: true, completion: {
self.streamController.player?.play()
})
}
I would just like this audio stream to play when the user taps the play button, and pause when they tap the pause button, not open a new view that shows as if it's a video.

Related

Swiftui - Play background music with other sound effects and toggle audio button

I have following Code for Audio Player in SwiftUI.
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSound(sound: String, type: String) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.play()
} catch {
print("ERROR: Could not find and play the sound file!")
}
}
}
To Play the sound in Content view its called as.
playSound(sound: "filename", type: "mp3")
Issue is. I add background music mp3. It works fine. But now I assign a click button sound using same command, which stops the background music,
How can I continue playing the background music along with other one off sound effects.
As a bonus how can I create a button which mute/unmute background music within the app.
Thank you so much.

Using an AVPlayer returns a "non-Multipath connection" error

I'm using AVKit to play a youtube URL.
I have this code inside a button action:
#IBAction func trailerButtonAction(_ sender: Any) {
guard let youtubeUrl = youtubeURL else { return }
let player = AVPlayer(url: youtubeUrl)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true) {
player.play()
}
}
The URL is valid, but when I press the button, the video doesn't stop loading and I'm getting this message on Debug area:
nw_endpoint_flow_copy_multipath_subflow_counts Called on non-Multipath connection
Edit:
I found that AVPlayer doesn't support youtube URL
I would say this log isn't necessarily relevant. I was getting this error when trying to playback on the simulator but it wasn't happening on a real device.
One workaround would be to use a 12.4.x simulator as it does not exhibit this issue. Only the 13.x simulators are showing this error. It happens to repeatedly that it slows down Simulator to a craw until all requested tracks have been buffered.
To combat this while testing, I am either not turning on AVPlayer or I am only buffering a short track.
To cut down on the number of errors try initing your AVPlayer like so:
var avPlayer : AVPlayer = AVPlayer()
This may cut down the errors by 30%.

TVOS getting ReferenceError: Can't find variable when calling SWIFT function

I am trying to playback youtube videos with tvml on my appleTV. It is based on:
https://gist.github.com/nickv2002/b7bb28cdccc000bdb910
The first time I start it, it is working, but after I play around (leaving the app), I get:
ReferenceError: Can't find variable: playYTblock
After rebooting/exit(0)ing the app the ATV it is working again... it seems, the context between the app<>tvjs is lost - anyone with ideas?
Here is my code:
in AppDelegate.swift
let playerVC = YTPlayerViewController()
in the application function:
playerVC.createPlayYT( appController! )
in presenter.js
if (youtubeUrl && (event.type === "play")) {
playYTblock(youtubeUrl);
}
in the template.xml.js
<listItemLockup youtubeUrl="H4O6oEaIDrs">
btw has anyone an idea why the event.type === select is fired right after loading the template (without clicking on my side)
Can't answer about that exact problem but,
Here is what i'm using is to play youtube video on tvos :
pod "AKYoutubeParser"
A parser to retrieve the actual youtube video urls.
And the video playback is handled by apple core stuff (AVFoundation, AVKit)
you can delete all the hud part if you don't use it.
import AKYoutubeParser
import AVFoundation
import AVKit
func displayTrailer(trailer: String) {
AKYoutubeParser.h264Streams(trailer) { [weak self] streams, error in
if let s = streams, v = AKYoutubeParser.getBestQuality(s) {
let playerVC = AVPlayerViewController()
let playerItem = AVPlayerItem(asset: AVAsset(URL: v.url))
let videoPlayer = AVPlayer(playerItem: playerItem)
playerVC.player = videoPlayer
self?.presentViewController(playerVC, animated: true) {
playerVC.player?.play()
}
}
}
}

Can play a sound effect on apple watch simulator now?

I want to play a sound when user press on the button on WKInterfaceController. Here is how I did in my project:
- Add a AVFoundation frame work to my watchkit app.
- Import AVFoundation on my WKInterfaceController
- Create 2 variable for audio session and player:
var audioSession:AVAudioSession!
var player:AVAudioPlayer!
- make 2 function for configure an audio session and configure Audio Player:
func configureAudioSession() {
self.audioSession = AVAudioSession.sharedInstance()
var categoryError:NSError?
var activeError:NSError?
// set category cho audio session
self.audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &categoryError)
println("error: \(categoryError)")
// set active cho audio session
var success = self.audioSession.setActive(true, error: &activeError)
if !success {
println("error making audio session active :\(activeError)")
}
}
func configureAudioPlayer() {
// Lay song path
var songPath = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3")
// Chuyen thanh URL
println("songpath: \(songPath)")
var songURL = NSURL(fileURLWithPath: songPath!)
println("songURL: \(songURL)")
//
var songError:NSError?
// Tao audioplayer
self.player = AVAudioPlayer(contentsOfURL: songURL!, error: &songError)
println("songerror:\(songError)")
self.player.numberOfLoops = 0
}
After that i finish my button press function like this:
#IBAction func startGameButtonPressed() {
self.configureAudioSession()
self.configureAudioPlayer()
self.player.play()
}
Every thing's working fine , I can saw the southPath although my button is working but I cannot hear the sound. I still use these steps on IOS app and it's working fine. May be we can't play a sound effect on Watchkit at this time? If we can, please help me to do that.
No. It is not possible to play sounds with WatchKit on the Apple Watch.
- Apple's WatchKit Evangelist
It is not currently possible to play sounds using the latest build of WatchKit.
I would suggest submitting a feature request.
YEs its possible to play a sound file in apple watch application.You need to add the sound file separately in apple watch application extension and the call the AVAudioPlayer to play the sound file.
e.g:
let path = NSBundle.mainBundle().pathForResource("coinFlip", ofType:"caf")
let fileURL = NSURL(fileURLWithPath: path!)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()

AVFoundation playing audio in background/on lock screen in Swift

I'm trying to find a way with AVFoundation to play audio when the user is on the lock screen or if they lock the app in the middle of using my app
class ViewController: UIViewController, AVAudioPlayerDelegate {
var avPlayer: AVAudioPlayer?
var error: NSError?
... other stuff ...
func playChime(fileName: String) -> Void {
let fileURL: NSURL! = NSBundle.mainBundle().URLForResource(fileName, withExtension: "wav")
self.avPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
self.avPlayer?.play()
}
... other stuff ...
}
What needs to be added to this to ensure sounds play when the user is on the lock screen as well?
To continue playing audio in the background when the device is locked or on the home screen (on Xcode 6.3):
Add to your ViewController:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
Then in your Info.plist, add a new entry for UIBackgroundModes and set it to audio. Xcode will automatically fill it out as 'Require background modes' and 'App plays audio or streams audio/video using Airplay'