Audio not working on device. Does work on simulator

I have created a Sound class and placed a method in my scene file to call the audio when the view begins.

I have also linked the AudioToolbox.framework in the Build Phase.

All runs fine on my simulator but the sound does not play on an actual device.

static let sharedInstance = Sound()

private let music = “filename.mp3”

private var player = AVAudioPlayer()
private var initialized = false

func playMusic() {
let url = URL(fileURLWithPath: Bundle.main.path(forResource: “filename”, ofType: nil)!)

do {
    player = try AVAudioPlayer(contentsOf: url)
} catch let error as NSError {
    NSLog("Error playing music: %@", error)
}

player.numberOfLoops = -1
player.prepareToPlay()
player.play()

initialized = true

}

One thing you can check is that the file name matches exactly, including case. The simulator is case insensitive for loading files from the bundle, but the device is not.

Hi,
I have the same problem (in 2020 :slight_smile: )
All my sound effects and backing audio work fine on the simulator but not on my cell (even unplugged from the computer and usb cable).
I have checked the case file names but everything match.
I tried with .mp3 and .wav, and also move the audio from my ‘audio’ folder in the bundle and put the files next the swift files.
Nothing seems to work.

Is there a framework to manually add in the ‘link binary with librairies’ beside ‘import AVFoundation’ in the swift files?

Did someone solve this problem?

(I’m working with xCode 11.4)

1 Like

Problem solve! :man_dancing:

I completely switched off my cell and restart it and the sound is now playing.
All sound effects and backing audio.
I didn’t change anything in the code.
Maybe a reset was necessary for testing the app on device…

I hope this will help.

Hi @lewis-h,
it is an AudioPlayer, how do you manage to get Video showing on that?

@philport Glad you sorted it out! Cheers! :]