macosaudioswiftuisystem-sounds

How to play Play a system sound with macOS SwiftUI


I am trying to play a system sound with a MacOS SwiftUI application. What I wish is just to play a system sound when an image appears...

My code (part of it) is the following

import Foundation
import Cocoa
import SwiftUI
import AVFoundation
...
Image("OK Done")
   .resizable()
   .frame(width: 100, height: 100)
   .offset(x: 40, y: 0)
   .opacity(OKisVisible ? 1.0 : 0.0)
   .onAppear {
/*    AudioServicesPlaySystemSound(1108)        This works on iOS only */
      AudioServicesPlayAlertSound(1108)         // This does not work on macOS Ventura 13.2.1
   }
...

Any suggestion ? Thanks


Solution

  • Apple changes up the installed assets with each Mac OS version. Anything undocumented might not be reliable or approved for the Mac Store, as I understand. The only MacOS system sounds that can be used are those documented, System Sounds in Apple's documentation, i.e. kSystemSoundID_FlashScreen and kSystemSoundID_UserPreferredAlert.

    The following is example code using one of those sounds:

    import SwiftUI
    import AudioToolbox
    
    struct ContentView: View {
        var body: some View {
            Image("OK Done")
                .resizable()
                .frame(width: 100, height: 100)
                .onAppear {
                    AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_UserPreferredAlert))
                }
        }
    }