Bundle.main.url/path cannot locate audio file.

Hii,

I wanted to use some audio files for my project that I'm building for Swift Student Challenge. But when I'm trying to locate the audio file I get an error or crash because the playground cannot locate or find the path to that audio file. I'm using Xcode app playground project.

My code :

func playSound(soundName:String){

    if let url = Bundle.main.url(forResource: "CFile", withExtension: "mp3"){
        do {
            self.audioPlayer = try AVAudioPlayer(contentsOf: url)
            self.audioPlayer?.prepareToPlay()
            self.audioPlayer?.play()
        }catch {
            print("Error : \(error)")
        }
    }
    else{
        print("ERROR")
    }
    //        let url = Bundle.main.url(forResource: "C", withExtension: "wav")
    //        audioPlayer = try! AVAudioPlayer(contentsOf: url!)
    //        self.audioPlayer.play()
}

}

If anyone has a solution please help me to fix this thing because sound is an important part of my project.

Thank you!!!

Answered by CMDdev in 751054022

Hi!

Is your sound file placed inside the Resources folder? For me, it works fine when I place it there.

If you don't see a Resources folder, add your audio files using the plus button in the bottom right corner (or simply drag and drop it). The folder will be automatically made for you.

Good luck!

Accepted Answer

Hi!

Is your sound file placed inside the Resources folder? For me, it works fine when I place it there.

If you don't see a Resources folder, add your audio files using the plus button in the bottom right corner (or simply drag and drop it). The folder will be automatically made for you.

Good luck!

Bundle.main.url/path cannot locate audio file.
 
 
Q