iosobjective-caudioswift

Creating and playing a sound in swift


So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?

It would be like this for Objective-C:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);

And then to play it I would do:

AudioServicesPlaySystemSound(Explosion);

Does anyone know how I could do this?


Solution

  • Here's a bit of code I've got added to FlappySwift that works:

    import SpriteKit
    import AVFoundation
    
    class GameScene: SKScene {
    
        // Grab the path, make sure to add it to your project!
        var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
        var audioPlayer = AVAudioPlayer()
    
        // Initial setup
        override func didMoveToView(view: SKView) {
            audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
            audioPlayer.prepareToPlay()
        }
    
        // Trigger the sound effect when the player grabs the coin
        func didBeginContact(contact: SKPhysicsContact!) {
            audioPlayer.play()
        }
    
    }