What can I do to fix this error? - swift

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

Related

Swift 3: AVAudioPlayer not playing sound

I have a struct with my audio player in it:
struct MT_Audio {
func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) {
var audioPlayer = AVAudioPlayer()
if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
let audioURL = URL(string:audioPath)
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
audioPlayer.volume = atVolume
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
}
//I'm calling it in viewDidLoad like this:
guard let fileURL = Bundle.main.url(forResource:"heartbeat-01a", withExtension: "mp3")
else {
print("can't find file")
return
}
let myAudioPlayer = MT_Audio() //<--RESOLVED THE ISSUE BY MAKING THIS A PROPERTY OF THE VIEWCONTROLLER
myAudioPlayer.playAudio("heartbeat-01a", "mp3", 1.0)
Since it doesn't crash and burn on the guard I know the file is there. I've also put a break point in after the try and I am getting to the audio player. When I go to the actual file and click on it in Xcode it plays. This fails on both the sim and device. Any help would be appreciated.
Looks like your audioPlayer is only stored within your playAudio function.
Try to keep the audioPlayer as an variable inside your class like this:
struct MT_Audio {
var audioPlayer: AVAudioPlayer?
mutating func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) {
// is now member of your struct -> var audioPlayer = AVAudioPlayer()
if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
let audioURL = URL(string:audioPath)
do {
let audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
audioPlayer.volume = atVolume
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
}

Why do I keep getting this error??? fatal error: unexpectedly found nil while unwrapping an Optional value

I am trying to create an app with sound built in. Whenever I try to build my program I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is my code:
var magicSound: AVAudioPlayer = AVAudioPlayer()
#IBOutlet var Answer: UILabel!
var AnswerArray = ["Yes", "No", "Maybe", "Try Again", "Not Now", "No Doubt", "Yes Indeed", "Of course", "Definetley Not"]
var chosenAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: ".wav")
do {
try magicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile!))
}
catch {
print(error)
}
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event?.subtype == motion {
printAnswer()
randomAnswer()
animation()
showingAnswerAnimation()
magicSound.play()
}
}
The console throws the error at the line,
try magicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile!))
If anyone could help me fix my code that would be great.
I believe the line:
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: ".wav")
should be:
let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav")
The dot character is implicit in to the type parameter.
This is how I would write it:
if let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav") {
let magicSound = try? AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile))
}
else {
print( "MagicSound.wav does not exist in main bundle" )
}
Make sure that the file name is an exact case-sensitive match.Also make sure the resource file is at the top level of the bundle (i.e. in the same folder as the .xcodeproj and .xcworkspace file).
Okay this unexpected found nil while unwrapping an Optional value is pretty common errors in SO. You should search more before posting the question.
This magicFile! is the main culprit here. The use of ! means you are unwrapping such a value that you are cent percent sure that the value does contain something other than nil. But if the value is nil your code is supposed to crash and give you a hint that you're assuming something wrong about the value. So change it.
Now comes the rescue. You have multiple options to safely unwrap an Optional value. Such as optional-binding. Having said that you should change your implementation like:
if let magicFile = Bundle.main.url(forResource:"MagicSound" withExtension:"wav") { //As you are supposed to use url, no need to have the path as String
do {
try magicSound = AVAudioPlayer(contentsOf: magicFile)
}
catch {
print(error)
}
}
Try using below Code hope it helps
func playSound() {
guard let url = Bundle.main.url(forResource: "MagicSound", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = magicSound else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
and make sure to import AVFoundation use this

Does anybody know how to fix Do-Try-Catch error code= EXC_1386_INVOP in swift?

I'm writing calculator app in swift when I tried to add audio file I put this above the calc programming:
var player:AVAudioPlayer = AVAudioPlayer()
#IBAction func play(_ sender: UIButton)
{
player.play()
}
and down below in view did load I put this. Please, any help will be great!
override func viewDidLoad() {
super.viewDidLoad()
//Do any additional setup after loading the view, typically from a nib.
do
{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp4")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{
// error
abort()
}
}
you are retreiving path Not the URL... secondly your do try Syntax is wrong... try this code
do
{
let audioPath = Bundle.main.url(forResource: "song", withExtension: "mp4")
player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{

Swift 3 enum in functions causes app to crash

I'm trying to play a sound based on file name. I created an enum with all file names. Everything works, except this case, where I check for the soundType.click
func playSound(type: soundType) {
var soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!)
if type.rawValue == soundType.click.rawValue {
soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "wav")!)
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundUrl)
audioPlayer.play()
} catch _ { }
}
And here is my enum
enum soundType: String {
case selectAnswer = "answerSelected"
case correctAnswer = "correctAnswer"
case wrongAnswer = "wrongAnswer"
case click = "click"
}
The problem is here where I check for "type.rawValue == soundType.click.rawValue"
Here is the error
fatal error: unexpectedly found nil while unwrapping an Optional value
You should take a look at this line of code first.
var soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!)
soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "wav")!)
Here, you are force unwrapping a failable initializer. You should check if Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!) exists first by doing something like this...
if let soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")){
if type.rawValue == soundType.click.rawValue {
...
}
or you could also use a guard statement..
Check this blog post by Natashtherobot to learn more about how to unwrap stuff well. https://www.natashatherobot.com/swift-guard-better-than-if/

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.