Bundle.main.path(forResource:ofType:inDirectory:) returns nil

后端 未结 10 2430
遥遥无期
遥遥无期 2020-12-07 13:08

Try not to laugh or cry -- I\'m just getting back into coding after 20 years out...

I\'ve spent more than 4 hours looking at references and trying code snippets to g

10条回答
  •  借酒劲吻你
    2020-12-07 13:53

    Same problem, slightly different situation & solution. I'm following a tutorial that said to use the following code:

        // Start the background music:
        if let musicPath = Bundle.main.path(forResource:
            "Sound/BackgroundMusic.m4a", ofType: nil) {
            print("SHOULD HEAR MUSIC NOW")
            let url = URL(fileURLWithPath: musicPath)
    
            do {
                musicPlayer = try AVAudioPlayer(contentsOf: url)
                musicPlayer.numberOfLoops = -1
                musicPlayer.prepareToPlay()
                musicPlayer.play()
            }
            catch { print("Couldn't load music file") }
        }
    }
    

    I had the same issue as others but none of the solutions fixed the issue. After experimenting, all I did was remove Sound from the path in the following call and everything worked:

    Bundle.main.path(forResource: "BackgroundMusic.m4a", ofType: nil)
    

    It would seem that the tutorial was in error by telling me to include Sound in the path.

提交回复
热议问题