As you see I'm streaming an audio broadcast. But when I press the home button and exit the app streaming stops or I cannot hear. How can I continue streaming in background and listen it from lock screen?
ViewController.Swift
import UIKit
import AVFoundation
import MediaPlayer
import GoogleMobileAds
class ViewController: UIViewController, GADInterstitialDelegate {
#IBOutlet weak var exitMapButton: UIButton!
#IBOutlet weak var radarMap: UIWebView!
var interstitial: GADInterstitial!
func createAndLoadInterstitial() -> GADInterstitial {
var interstitial = GADInterstitial(adUnitID: "adUnitID-XXXX")
interstitial.delegate = self
interstitial.loadRequest(GADRequest())
return interstitial
}
func getAd(){
if (self.interstitial.isReady)
{
self.interstitial.presentFromRootViewController(self)
self.interstitial = self.createAndLoadInterstitial()
}
}
#IBOutlet weak var ataturkButton: UIButton!
#IBOutlet weak var sabihaButton: UIButton!
#IBOutlet weak var esenbogaButton: UIButton!
#IBOutlet weak var weatherButton: UIButton!
#IBOutlet weak var statusLabel: UILabel!
#IBOutlet weak var playButton: UIButton!
#IBOutlet weak var webViewButton: UIButton!
var googleBannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
}
class PlayerAv {
var audioLink: String?
var player: AVPlayer
init(link: String) {
self.audioLink = link
self.player = AVPlayer(URL: NSURL(string: link))
}
}
var myPlayer = PlayerAv(link: "http://somewebsite.com/abc.pls")
var setTowerState = ""
#IBAction func sliderValueChanged(sender: UISlider) {
var currentValue = Float(sender.value)
println(currentValue)
myPlayer.player.volume = currentValue
}
#IBAction func getWeatherWindow(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://somewebpage.com")!)
println("Directed to weather page")
}
#IBAction func changeToAtaturk() {
myPlayer.player.pause()
myPlayer = PlayerAv(link: "http://somewebsite.com/abc.pls")
myPlayer.audioLink == ""
println("\(myPlayer.audioLink!)--a")
playButton.setTitle("Pause", forState: UIControlState.Normal)
myPlayer.player.play()
setTowerState = "ataturk"
statusLabel.text = "Status: Playing, LTBA"
}
#IBAction func changeToEsenboga() {
myPlayer.player.pause()
myPlayer = PlayerAv(link: "http://somewebsite.com/def.pls")
println("\(myPlayer.audioLink!)--a")
playButton.setTitle("Pause", forState: UIControlState.Normal)
myPlayer.player.play()
setTowerState = "esenboga"
statusLabel.text = "Status: Playing, LTAC"
}
#IBAction func changeToSabiha() {
myPlayer.player.pause()
myPlayer = PlayerAv(link: "http://somewebsite.com/efg.pls")
println("\(myPlayer.audioLink!)--a")
playButton.setTitle("Pause", forState: UIControlState.Normal)
myPlayer.player.play()
setTowerState = "sabiha"
statusLabel.text = "Status: Playing, LTFJ"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playButtonPressed(sender: AnyObject) {
toggle()
}
func toggle() {
if playButton.titleLabel?.text == "Play" {
playRadio()
println("Playing")
statusLabel.text = "Status: Playing"
} else {
pauseRadio()
println("Paused")
statusLabel.text = "Status: Paused"
}
}
func playRadio() {
myPlayer.player.play()
playButton.setTitle("Pause", forState: UIControlState.Normal)
}
func pauseRadio() {
myPlayer.player.pause()
playButton.setTitle("Play", forState: UIControlState.Normal)
}
}
You need to set your app Capabilities Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active
From Xcode 11.4 • Swift 5.2
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
Xcode 10.2.1 Swift 4
Please add the following code in your AppDelegate
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
return true
}
Note: - Please configure options as required. E.g to stop a background audio while a video file being played add
options: [.allowAirPlay, .defaultToSpeaker]
And don't forget to enable audio and airplay in Background mode
Only paste on the viewDidload
let path = Bundle.main.path(forResource:"Bismallah", ofType: "mp3")
do{
try playerr = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
} catch {
print("File is not Loaded")
}
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch{
}
player.play()
Swift 5 Xcode 11.2.1
Add this code where you have initialized the AudioPlayer.
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSession.Category.playback)
}
catch{
fatalError("playback failed")
}
Related
As a beginner, I am unable to figure out why I get this error. The code I am using comes directly from the Udacity course I am taking. Here is the code:
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController, <AVAudioRecorderDelegate> {
var audioRecorder: AVAudioRecorder!
#IBOutlet weak var recordingLabel: UILabel!
#IBOutlet weak var recordbutton: UIButton!
#IBOutlet weak var stopRecordingButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
stopRecordingButton.isEnabled = false
}
#IBAction func recordAudio(_ sender: Any) {
recordingLabel.text = "Recording in progress..."
recordbutton.isEnabled = false
stopRecordingButton.isEnabled = true
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
let recordingName = "recordedVoice.wav"
let pathArray = [dirPath, recordingName]
let filePath = URL(string: pathArray.joined(separator: "/"))
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record() }
#IBAction func stopRecording(_ sender: Any) {
recordbutton.isEnabled = true
stopRecordingButton.isEnabled = false
recordingLabel.text = "Tap to Record"
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: BOOL) {
print("finished recording")
}
}
I appreciate any help you cold give me. XCode 11.5, Swift 5.2
Thanks,
Mike
You should get a bunch of more errors.
Anyway this is not Objective-C. Adopting protocols is not in angle brackets
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
and the boolean type in Swift is Bool (not BOOL)
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
And don't try!. Catch errors.
I am trying to playback the recorded session in full view after it is recorder.
Kind of like "snapchat".
I can record and play the videoplay back in a UIView, but it is shown with "play", "Done" "Stop" buttons. I don't want that. I want it to look like snapchat.
This is my code, where i found Here, but I modified a tiny little bit. :)
import UIKit
import AVFoundation
import AssetsLibrary
import Photos
import MediaPlayer
import AVKit
class Camera: UIViewController, AVCaptureFileOutputRecordingDelegate {
#IBOutlet var cameraView: UIView!
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice:AVCaptureDevice!
var CamChoser = false
var moviePlayer: MPMoviePlayerController?
#IBOutlet weak var playback: UIView!
#IBOutlet weak var exitCameraModeButton: UIButton!
#IBAction func exitCameraModeButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
var captureSession = AVCaptureSession()
lazy var cameraDevice: AVCaptureDevice? = {
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]
return devices.filter{$0.position == .Front}.first
}()
lazy var micDevice: AVCaptureDevice? = {
return AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
}()
var movieOutput = AVCaptureMovieFileOutput()
private var tempFilePath: NSURL = {
let tempPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("tempMovie").URLByAppendingPathExtension("mp4").absoluteString
if NSFileManager.defaultManager().fileExistsAtPath(tempPath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(tempPath)
} catch { }
}
return NSURL(string: tempPath)!
}()
private var library = ALAssetsLibrary()
//private var library = PHPhotoLibrary()
#IBOutlet weak var switchCameraButton: UIButton!
#IBAction func switchCameraButton(sender: AnyObject) {
//startSession()
}
override func viewDidLoad() {
super.viewDidLoad()
//start session configuration
captureSession.beginConfiguration()
captureSession.sessionPreset = AVCaptureSessionPresetHigh
let devices = AVCaptureDevice.devices()
startSession()
}
func startSession() {
// add device inputs (front camera and mic)
print(CamChoser)
captureSession.addInput(deviceInputFromDevice(cameraDevice))
captureSession.addInput(deviceInputFromDevice(micDevice))
// add output movieFileOutput
movieOutput.movieFragmentInterval = kCMTimeInvalid
captureSession.addOutput(movieOutput)
// start session
captureSession.commitConfiguration()
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.cameraView.layer.addSublayer(previewLayer!)
self.cameraView.bringSubviewToFront(self.exitCameraModeButton)
self.cameraView.bringSubviewToFront(self.switchCameraButton)
previewLayer?.frame = self.cameraView.layer.frame
captureSession.startRunning()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("touch")
// start capture
movieOutput.startRecordingToOutputFileURL(tempFilePath, recordingDelegate: self)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("release")
//stop capture
movieOutput.stopRecording()
let videoUrl = movieOutput.outputFileURL
moviePlayer = MPMoviePlayerController(contentURL: videoUrl)
moviePlayer!.movieSourceType = MPMovieSourceType.Unknown
moviePlayer!.view.frame = playback.bounds
moviePlayer!.scalingMode = MPMovieScalingMode.AspectFill
moviePlayer!.controlStyle = MPMovieControlStyle.Embedded
moviePlayer!.shouldAutoplay = true
playback.addSubview((moviePlayer?.view)!)
//moviePlayer!.prepareToPlay()
moviePlayer?.setFullscreen(true, animated: true)
moviePlayer!.play()
cameraView.bringSubviewToFront(playback)
}
private func deviceInputFromDevice(device: AVCaptureDevice?) -> AVCaptureDeviceInput? {
guard let validDevice = device else { return nil }
do {
return try AVCaptureDeviceInput(device: validDevice)
} catch let outError {
print("Device setup error occured \(outError)")
return nil
}
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
if (error != nil) {
print("Unable to save video to the iPhone \(error.localizedDescription)")
} else {
// save video to photo album
library.writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: { (assetURL: NSURL?, error: NSError?) -> Void in
if (error != nil) {
print("Unable to save video to the iPhone \(error!.localizedDescription)")
}
})
}
}
}
Just so you know, MPMoviePlayerController has been deprecated for iOS 9. The issue is your control style is set to embedded which by default, displays the control buttons. Use MPMovieControleStyle.None to remove the controls.
See MPMovieControlStyle documentation for more details.
When I open a view the music starts playing using AVFoundation and then when it finishes, how do I create an action when it stops? So when the music file finishes, I want the "Pause" button turn into "Play". I know already how to change the text programmatically by using btnPausePlay.setTitle("Pause", forState: UIControlState.Normal)but how do I create the function when the music stops playing?
Note: I'm using swift
You can use delegate functions for that and here is your complete code:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var player = AVAudioPlayer()
#IBOutlet weak var musicSlider: UISlider!
#IBOutlet weak var btnPausePlay: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
musicSlider.value = 0.0
music()
}
func updateMusicSlider(){
musicSlider.value = Float(player.currentTime)
}
#IBAction func sliderAction(sender: AnyObject) {
player.stop()
player.currentTime = NSTimeInterval(musicSlider.value)
player.play()
}
func music(){
var audioPath = NSBundle.mainBundle().pathForResource("1", ofType: "mp3")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
musicSlider.maximumValue = Float(player.duration)
var timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
player.delegate = self
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
}
//This delegate method will call when your player finish playing.
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool)
{
btnPausePlay.setTitle("Play", forState: .Normal)
}
}
And HERE is your sample project for more Info.
I have created a sound player in swift with AVFoundation. I am trying to start the next song in array when the playing song is finished. I was trying to implement this code
if (audioPlayer.currentTime >= audioPlayer.duration){
var recentSong = songPlaylist[selectedSongNumber + 1]
audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
audioPlayer.play()
}
but I am not being able to implement this code (I do not know where to implement it).Here is my complete code
import UIKit
import AVFoundation
import AVKit
public var audioPlayer = AVPlayer()
public var selectedSongNumber = Int()
public var songPlaylist:[String] = ["song1", "song2"]
public var recentSong = "song1"
let playImage = UIImage(named: "Play.png") as UIImage!
let pauseImage = UIImage(named: "Pause.png") as UIImage!
class FirstViewController: UIViewController {
#IBOutlet weak var musicSlider: UISlider!
#IBOutlet weak var PlayPause: UIButton!
var audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
override func viewDidLoad() {
super.viewDidLoad()
musicSlider.maximumValue = Float(audioPlayer.duration)
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
if (audioPlayer.currentTime >= audioPlayer.duration){
var recentSong = songPlaylist[selectedSongNumber + 1]
audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
NSBundle.mainBundle().pathForResource(recentSong, ofType: "mp3")!), error: nil)
audioPlayer.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func PlayPauseButton(sender: AnyObject) {
if (audioPlayer.playing == false){
audioPlayer.play()
PlayPause.setImage(pauseImage, forState: .Normal)
}else{
audioPlayer.pause()
PlayPause.setImage(playImage, forState: .Normal)
}
}
#IBAction func StopButton(sender: AnyObject) {
audioPlayer.stop()
audioPlayer.currentTime = 0
PlayPause.setImage(playImage, forState: .Normal)
}
#IBAction func musicSliderAction(sender: UISlider) {
audioPlayer.stop()
audioPlayer.currentTime = NSTimeInterval(musicSlider.value)
audioPlayer.play()
}
func updateMusicSlider(){
musicSlider.value = Float(audioPlayer.currentTime)
}
}
I am updating my code with something different:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var counter = 0
var song = ["1","2","3"]
var player = AVAudioPlayer()
#IBOutlet weak var musicSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
musicSlider.value = 0.0
}
func updateMusicSlider(){
musicSlider.value = Float(player.currentTime)
}
#IBAction func playSong(sender: AnyObject) {
music()
}
#IBAction func sliderAction(sender: AnyObject) {
player.stop()
player.currentTime = NSTimeInterval(musicSlider.value)
player.play()
}
func music(){
var audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "mp3")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
musicSlider.maximumValue = Float(player.duration)
var timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
player.delegate = self
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool)
{
println("Called")
if flag {
counter++
}
if ((counter + 1) == song.count) {
counter = 0
}
music()
}
}
You can do it this way.
Hope It will help and HERE is sample project for more Info.
You need to implement AVAudioPlayerDelegate Protocol's method:
optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer!, successfully flag: Bool)
Documentation link
Play your next music item here.
But I will not recommend, since AVAudioPlayer can only play one item at a time. You need to instantiate again with another music item after completion. I will suggest you to use AVQueuePlayer. Detaled answer has been given here. Hope it helps!
I created a sound player in swift with AVFoundation. I used progressView to time the song and then when it hits 0.98743 it will update to the next song automatically this is the Github link: https://github.com/ryan-wlr/MusicPlayerIOS
func updateProgressView() {
if (progressView.progress > a.advanced(by: 0.98743)) {
audioPlayerDidFinishPlayeing()
}
if audioPlayer.isPlaying {
let progress = Float(audioPlayer.currentTime/audioPlayer.duration)
progressView.setProgress(progress, animated: true)
}
}
What I am trying to do is have a settings page in my app and when a switch is clicked on (its original state is off) then it will mute the entire app. So far what my code can do is mute only the current view and it works great until I either segue to my main view then that music is still playing that is associated with that and when I segue back to the settings page the mute switch is returned to its original off state and the music is playing once again. I was wondering how to fix my code so that when turned on it mutes all noise. Here is my code thank you for reading and helping:
import UIKit
import AVFoundation
var songs = ""
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer =
AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
class settingsView: UIViewController {
#IBOutlet weak var mySwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
playBackgroundMusic(songs)
if mySwitch.on {
backgroundMusicPlayer.pause()
} else {
backgroundMusicPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
songs = "settingsBackground.mp3"
switchPressed(self)
}
}
You can do it like this way:
MainViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off"{
if (backgroundMusicPlayer?.playing != nil){
backgroundMusicPlayer?.stop()
}
}else{
songs = "1.mp3"
playBackgroundMusic(songs)
}
}
}
settingsView.swift
import UIKit
class settingsView: UIViewController {
#IBOutlet weak var mySwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
if mySwitch.on {
NSUserDefaults().setObject("on", forKey: "playerStatus")
playBackgroundMusic(songs)
} else {
NSUserDefaults().setObject("Off", forKey: "playerStatus")
backgroundMusicPlayer!.stop()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off" {
mySwitch.setOn(false, animated: false)
}
}
}
Here is complete working project : https://github.com/DharmeshKheni/Switch-with-AudioPlayer