Playing music in Swift: Unexpectedly found nil while unwrapping an Optional value - swift

Working on a project, I decided to add some music to play when a certain action is triggered. Here's what I've got:
var player : AVAudioPlayer?
several lines later...
func playSound(){
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Kalimba", ofType: "wav")!)
print(alertSound)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! player = AVAudioPlayer(contentsOf: alertSound)
player!.prepareToPlay()
player!.play()
}
Whenever I try this, xcode throws me a fatal error when the action is triggered, saying:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

You should check with your music file is attached with your target? -
let path = Bundle.main.path(forResource: "Kalimba", ofType: "wav")
if path != nil {
let url = URL(fileURLWithPath: path!)
print(url)
let player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
} else {
print("File Not exist")
}

Related

AVFoundation bugs, No sound when I run audioPlayer.play()

I have a little problem with AVFoundation, when I launch a sound there is nothing that comes out. On the other hand it is enough to add a timer that displays the currentTime of the sound in question and everything works correctly. could you help me? Thanks.
code that does not work:
do {
let path = Bundle.main.path(forResource: "sound1", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.volume = 1.0
audioPlayer.play()
} catch {
assertionFailure("Failed crating audio player: \(error).")
return
}
just add the timer and everything will work:
do {
let path = Bundle.main.path(forResource: "sound1", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.volume = 1.0
audioPlayer.play()
print("le son est en cours de lecture !")
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
print(audioPlayer.currentTime)
}
} catch {
assertionFailure("Failed crating audio player: \(error).")
return
}
This worked for me
instead of
let audioPlayer = try AVAudioPlayer(contentsOf: url)
change to
audioPlayer = try AVAudioPlayer(contentsOf: url)

SceneKit – AVPlayer material crash

I'm using a video as the material for an SCNNode:
geo.materials.first?.diffuse.contents = AVPlayer(url: url)
This works fine on most iOS devices but crashes on the older iPhone 5s with the following error:
-[MTLTextureDescriptorInternal validateWithDevice:], line 781: error 'MTLTextureDescriptor has invalid pixelFormat (520).'
-[MTLTextureDescriptorInternal validateWithDevice:]:781: failed assertion `MTLTextureDescriptor has invalid pixelFormat (520).'
Is there a fix/workaround for this issue?
I think it's a hardware issue of iPhone 5s. Try to use a SKVideoNode as a workaround. SpriteKit's objects are much "lighter" for iPhone 5s.
var videoNode: SKVideoNode? = {
guard let urlString = Bundle.main.path(forResource: "file",
ofType: "m4v") else {
return nil
}
let url = URL(fileURLWithPath: urlString)
let item = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: item)
return SKVideoNode(avPlayer: player)
}()
Hope this helps.

Create a function from code

How do I create a function from this code in swift3?
I have a button which is pressed then plays this sound "push"
How can it be simplified when there are lots of buttons? I don't want to add all codes to every button.
var myAudio = AVAudioPlayer()
// Add sound
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: "push", ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
//call the sound
myAudio.play()
I made this change
func play(name : String){
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: name, ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
}
#IBAction func buttonFirst(_ sender: UIButton) {
play(name: "push")
myAudio.play()
}
#IBAction func buttonSecond(_ sender: UIButton) {
play(name: "second")
myAudio.play()
}
I got this output:
2017-07-25 16:13:23.270349+0100 sound[1728:933024] [aqme] 254: AQDefaultDevice (173): skipping input stream 0 0 0x0
Is that a problem?
I think you forgot the prepare
var audioPlayer = AVAudioPlayer()
let sound = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "mp3")!)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
You can use it in the following way
var myAudio : AVAudioPlayer?
func playSound(){
let path = Bundle.main.path(forResource: "push", ofType:"mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
self.myAudio = sound
sound.numberOfLoops = 1
sound.prepareToPlay()
sound.play()
} catch {
print("error loading file")
// couldn't load file :(
}
}
Furthermore you can use SwiftySound that lets you play sounds easily in Swift 3.
for example
Sound.play(file: "push.mp3")

What can I do to fix this error?

I get an error every time I try to run stating
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb).
Could someone explain why? heres the code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
player.play()
} catch {
// Process error here
}
}
}
This error is almost always caused by force unwrapping an object, i.e. the "!"operator. for your code, it's likely this line:
let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!
Chances are t can't find that file. To be safe with it and handle this error case, use this:
if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") {
/* do what you need to with the path*/
}
else{
/* handle error case */
}
You're force-unwrapping the optional in your line of code:
let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!
This file can returns an optional in case of not exist the resource, avoid the force unwrapping of the optional instead use optional-binding or a guard statement like in the following way. It's always recommend not make force-unwrapping of an optional because you're telling to the compiler that you know that always be different of nil and if it's happen you get an runtime error.
if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") {
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
player.play()
} catch {
// Process error here
}
}
Or with guard:
guard let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") else { return }
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
player.play()
} catch {
// Process error here
}
I hope this help you.
May be audio file not found. Try like this
if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3"){
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
player.play()
} catch {
// Process error here
}
}else{
print("path not found")
}

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.