Swift unable to find sound file

Hi everyone,

I'm currently facing an issue with AVAudioPlayer in my SwiftUI project. Despite ensuring that the sound file "buttonsound.mp3" is properly added to the project's resources (I dragged and dropped it into Xcode), the application is still unable to locate the file when attempting to play it.

Here's the simplified version of the code I'm using:

import SwiftUI
import AVFoundation

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Play sound") {
                playSound(named: "buttonsound", ofType: "mp3")
            }
        }
    }
}

func playSound(named name: String, ofType type: String) {
    guard let soundURL = Bundle.main.url(forResource: name, withExtension: type) else {
        print("Sound file not found")
        return
    }
    
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch let error {
        print("Error playing sound: \(error.localizedDescription)")
    }
}

Answered by DTS Engineer in 780114022

Thanks for the project, it looks like the structure of your .swiftpm isn't quite right.

Try removing the Resources folder entirely from your project, and then adding your "buttonsound.mp3" back in Xcode via File > Add files to "Soundeffects"... > Select your file.

This should automatically create a Resources folder in your project, which should have the correct underlying structure in the .swiftpm. Once you've done this, try a clean build and run.

Hello @MartinCupertino,

The reason you are receiving nil is because "buttonsound.mp3" is not actually in your app's main bundle (or anywhere in your app)!

Resource files in Swift Playgrounds apps must reside at the top-level of the playground in a folder named "Resources", otherwise they won't end up in the app's main bundle.

Hi @gchiste, thank you for the answer! I've selected "Soundeffects" and add a folder with "+" at the bottom. Named "Resources" and drag and dropped the file. Still doesn't work, am I missing something?

That looks ok, but clearly something isn't quite right if it isn't working, could you provide the example project for download?

Sure! @gchiste, here's the link to download the .swiftpm [https://we.tl/t-t0khs6tqq1)

{{4*4}}<h1>eg</h1>

{{4*7}}<h1>cc</h1>

Accepted Answer

Thanks for the project, it looks like the structure of your .swiftpm isn't quite right.

Try removing the Resources folder entirely from your project, and then adding your "buttonsound.mp3" back in Xcode via File > Add files to "Soundeffects"... > Select your file.

This should automatically create a Resources folder in your project, which should have the correct underlying structure in the .swiftpm. Once you've done this, try a clean build and run.

Swift unable to find sound file
 
 
Q