Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
like image 362
Peter Silie Avatar asked Dec 10 '16 13:12

Peter Silie


People also ask

How do I play sound through my screen Mac?

Make sure the cables from the display are connected to the ports on your Mac. Choose Apple menu > System Preferences, click Sound , then click Output. Make sure Display Audio is selected in the output device list.

Can I play audio from my iPhone on my Mac?

Play audio from iPhone on Macon the Lock Screen or in Control Center. Note: AirPlay to Mac is available on MacBook Pro (2018 and later), MacBook Air (2018 and later), iMac (2019 and later), iMac Pro (2017), Mac mini (2020 and later), and Mac Pro (2019) and works with iPhone 7 and later.

How do I play music through USB on Mac?

In the System Preferences window, click on the Sound (Speaker) icon. The Sound window will open. Click on the Input tab. Select USB Audio CODEC to set it as the Sound Input Device.


2 Answers

Swift 3 / 4 / 4.2 / 5 - Easiest solution:

NSSound(named: "customSound")?.play()
like image 64
ixany Avatar answered Oct 19 '22 11:10

ixany


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.

like image 45
El Tomato Avatar answered Oct 19 '22 12:10

El Tomato