Check if AVAudioPlayer is playing - swift

I've been trying to check if the AVAudioPlayer is currently playing, but when I try to do it in anyway it crashes.
I'm using stop button to stop the audio but when there is no audio playing it crashes.
How is it possible to check it in my stopaudio function ?
First I defined :
var audioPlayer = AVAudioPlayer()
I have stop button :
func stopaudio(sender: AnyObject){
audioPlayer.stop()
}
I tried to check like this :
if audioPlayer.playing{
audioPlayer.stop()
}
I am using the following code to play the audio :
var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("9", ofType: "m4a")!)!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()

The problem was because the AVAudioPlayer hasn't been initialized yet, so what i did to fix it is to initialize it and then stop it.
var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("013", ofType: "m4a")!)!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
audioPlayer.stop()

Declare a function in the ViewController class:
func tryAudio() {
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
} catch {
//handle errors
}
}
call tryAudio() to initialize the player before player.stop()

Related

Unable to play http audio using avaudioplayer in swift 4

I am trying to play simple audio from http url using AVAudioPlayer however getting weird error . Here is the code
func playSound() {
do {
let url = URL(string: "http://<domain>/stream")
var player = AVAudioPlayer() //tied to initialize it as AVAudioPlayer! too
player = try AVAudioPlayer(contentsOf: url!)
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}}
Error:
AddInstanceForFactory: No factory registered for id <CFUUID 0x6000030f4b00> F8BB1C28-BAE8-11D6-9C31-00039315CD46
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
You have to make player as global variable:
var player = AVAudioPlayer()
// ...
func playSound() { // ...

how can i add a progressbar to a mp3 player i created in swift using AVPlayer NOT AVAudioPlayer

here is my code of how im playing my mp3 from a live url i just cannot find any updated information for swift to use avplayer not avaudioplayer.. thank you in advance to all comments and helpers
var playerItem:AVPlayerItem?
var player = AVPlayer()
var error : NSError?
var sucess : Bool?
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,withOptions: .DefaultToSpeaker)
_ = try AVAudioSession.sharedInstance().setActive(true)
sucess = true
} catch let NotSucessError as NSError{error = NotSucessError
sucess = false}
if !sucess! {
NSLog("Fail to set audio session. Error:\(error)")
}
let url = NSURL(string: trackURL)
playerItem = AVPlayerItem(URL: url!)
player = AVPlayer(playerItem: playerItem!)
player.play()

fatal error: unexpectedly found nil while unwrapping an Optional value when using AudioPlayer in Swift 2

Hi I am trying to play a music file with a following code in swift 2. Basically I just dragged the audio file with a name f.mp3 to the asses folder and it my code breaks with the following message:
unexpectedly found nil while unwrapping an Optional value. Where exactly I need to put my mp3 file so the IOS can find it. Thank you
var audioPlayer: AVAudioPlayer! = nil
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play()
}
Your code is working fine with my project and here is my complete code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
playMyFile()
}
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Make sure your audio is added into Copy Bundle Resources like this:
If not added then add it this way:
Check THIS sample for more Info.

Swift AVPlayer to ear speaker

I've got a simple audio player that works great. I'm playing a remote URL MP3. My code:
#IBAction func playAudio(sender: AnyObject) {
let url = self.productAudio
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
player = AVPlayer(playerItem:playerItem)
player.
player.rate = 1.0;
player.play()
}
But the audio is outputed by the loud speaker. How can I play the audio through the ear speaker?
Swift 5.0
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(.playAndRecord)
try session.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
try session.setActive(true)
} catch {
print ("\(#file) - \(#function) error: \(error.localizedDescription)")
}
Finally I found the answer...
I had to modify my Audio Session, and override the port. This is the code before the player code:
let session = AVAudioSession.sharedInstance()
var error: NSError?
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: &error)
session.overrideOutputAudioPort(AVAudioSessionPortOverride.None, error: &error)
session.setActive(true, error: &error)

How do you make the music keep going even when going to a new ViewController in Swift?

I would like to play a mp3 file in a UIViewController. Though, when the user leaves the view controller the music stops. How do I keep it playing?
var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("musicFileHere", ofType: "mp3")!)!
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
Add audioPlayer.play so your whole code looks like this:
var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("musicFileHere", ofType: "mp3")!)!
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play