Play Sound in Swift SpriteKit project?
Asked Answered
S

3

8

When I run this code.

runAction(SKAction.playSoundFileNamed("Click.mp3", waitForCompletion: false))

My app was Crashed:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Resource Click.mp3 cannot be found in the main bundle'

Soane answered 6/11, 2014 at 12:24 Comment(4)
Did you properly added your Click.mp3 file?Gogol
note that ios filesystem is case-sensitive, ie click.mp3 and Click.mp3 refer to different filesPassion
After verifying that you have properly added and referred to the file in the code, clean and build your application.Jenn
Thank Everybody. I just Clean and build my app. it workedNicolnicola
P
17

verify that the file exists in the project. instantiates the variables in the file first and then make a method for breeding.

if the file exists in the project you should do the following:

var sound = SKAction.playSoundFileNamed("sound.mp3", waitForCompletion: false)
...
override func didMoveToView(view: SKView) {
    playSound(sound)
    //call playSound method when you want
}

func playSound(sound : SKAction)
{
    runAction(sound)
}

in this mode don't crash

Primo answered 6/11, 2014 at 13:19 Comment(0)
S
2

This may be the answer some people are looking for:

Audio files DO NOT go in Assets.xcassets!

I've had the same issue, and tried seemingly every slight code change as suggested by various StackOverflow answers, but nothing worked.

I only found this one answer that solved my issue: I had been adding my sound files to Assets.xcassets, where my graphics are. It turns out you need to add them to the project bundle (where the .swift files are, etc) — just drag the files to the Project Navigator list on the left of the screen.

Not sure why it's like this as it seems intuitive to include sound files as "Assets".

Spiccato answered 19/6, 2022 at 8:45 Comment(0)
U
0

I had this exact problem for the last hour! I had to go a different route, because I tried multiple things to get this simple line of code to work and failed. It's a little more code, but this solved my problem: https://mcmap.net/q/204031/-creating-and-playing-a-sound-in-swift.

Uptake answered 6/5, 2015 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.