How to add sound files to your bundle in Xcode?

Viewed 15626

I am trying to make an application with sound. I have asked a question before how to add sound to an app in Xcode but every time I run the app, the console throws this error, MagicSound.wav does not exist in main bundle when writing my code I basically told the program to crash the application and write MagicSound.wav does not exist in main bundle if it comes to be true. My question is how do you add a file (specifically a sound file) to your bundle in Xcode. I always assumed putting a file in your assets is the same thing as putting it in your bundle.

Here is my code,

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    
    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()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let magicFile = Bundle.main.path(forResource: "MagicSound", ofType: "wav") {
            _ = try? AVAudioPlayer(contentsOf: URL (fileURLWithPath: magicFile))
        }
        else {
            print( "MagicSound.wav does not exist in main bundle" )
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        
        if event?.subtype == motion {
            printAnswer()
            randomAnswer()
            animation()
            showingAnswerAnimation()
            magicSound.play()
        }
        
    }

If anybody could help that would be great!

Thanks.

4 Answers

There is an extra step here that XCode is doing implicitly, and it's possible to have your stuff configured in such a way that it doesn't get done. You need to make sure that the wav file is in the list of items under your target's Build Phases -> Copy Bundle Resources setting.

If you just have a main target for your app and nothing fancy, then this should be done automatically when you add the file to your folder in XCode. But I have a screwy setup where it's not, and I had to dig to find it.

Another thing to add, in addition to the other answers here is that when you import, you need to make sure it's copied to your app, in "Add to targets". This accomplishes the sound file being in "the list of items under your target's Build Phases -> Copy Bundle Resources setting."

You need to get all of these things right or it won't be in the Bundle.

Related