Playing sound in Xcode 9.2.

Hello!

I am having some issues with playing sound in Xcode 9.2. I tried watching few different tutorials and guides, but with no luck. Either code is outdated, my app crashes, or the sound just won't play or even plays for 0.1 second and then never again.

Here is my code, with comments for clarification.

import AVFoundation
  
    func updateDiceImages() {
      
        var soundEffect: AVAudioPlayer?
      
        let path = Bundle.main.path(forResource: "rollingDice.wav", ofType:nil)!
        let url = URL(fileURLWithPath: path)
      
        do {
            soundEffect = try AVAudioPlayer(contentsOf: url)
            soundEffect?.play()
        } catch {
            print(error)
        }
     

This is basically the part where sound is played. Every time a button is pressed, this function triggers. I can give you the whole code, but I didn't want to swamp people trying to help me out.

Thank you!


EDIT: I resolved the bug... I switched two classes up completely. 😕 Code above works as intentional.

Replies

// don't forget to import AudioToolbox

if let soundURL = Bundle.main.url(forResource: "soundName", withExtension: "extension") {

var mySound: SystemSoundID = 0

AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)

// Play

AudioServicesPlaySystemSound(mySound);

}

it will also help you .. it is more swifty
good luck