swiftmacosaudioavaudiosession

Playing a sound on macOS


I like to play a sound in my app. I found a lot of examples and also could compile and run them on Swift 3. But they are always for iOS. When imlementing this code in my app, AVAudioSession keeps undefined. What do I have to do? Is there something different for OSX?

import AVFoundation
...
    var audioPlayer = AVAudioPlayer()
    func PlaySound( ) {
        let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Sound", ofType: "mp3")!)
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch _ {
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch _ {
        }
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
        } catch _{
        }
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }

Solution

  • I've used the following function in conjunction with Swift 3 and a Cocoa project.

    import AVFoundation
    
    func playSound(file:String, ext:String) -> Void {
        let url = Bundle.main.url(forResource: file, withExtension: ext)!
        do {
            let player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }
    }
    

    // usage //

    playSound(file: "sound", ext: "caf") // where the file name is sound.caf.
    

    Make sure that the target membership checkbox is on when you select an audio file in your Xcode project.