Bundle.main.url(forResource: sound, withExtension: "wav", subdirectory: "Resources/Sounds") returns nil

Hi everyone, I'm trying to play sounds in my playground, but whenever I try to get the path, nothing comes out. I've tried everything possible to fix the error, but somehow it doesn't work

Here my Sound File:

import Foundation
import AVFoundation

var audioPlayer: AVAudioPlayer!

/// Play sounds
/// - Parameter sound: Sound filename
func playSound(sound: String) {
    let url = Bundle.main.url(forResource: sound, withExtension: "wav", subdirectory: "Resources/Sounds")
    
    guard url != nil else {
        print("error")
        return
    }
    
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url!)
        if !audioPlayer.isPlaying {
            audioPlayer?.play()
        } else {
            audioPlayer?.stop()
        }
    } catch {
        print(error)
    }
}
  • always I get the error print

  • What's the actual error you get?

Add a Comment

Replies

Maybe in the subdirectory, remove "Resources" as its probably already inside the Resources directory when searching for your file, so its effective trying to search for Resources/Resources/Sounds instead of just Resources/Sounds.

I have already try it out, but it don’t work