Skip to content

Sounds

Adding sound effects or short music clips to your app can enhance the user experience. This method is best suited for sound effects rather than full-length music tracks.

Keep in mind that adding multiple audio files will increase your app's size.

Implementation

  1. Create a Swift File
    • In Xcode, go to File > New > File From Template...
    • Select Swift File, name it SoundHandler.swift, and paste the following code:
swift
import AudioToolbox

class SoundHandler {
    var soundID: SystemSoundID = 0

    init(soundFileName: String, soundFileType: String) {
        if let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: soundFileType) {
            AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
        } else {
            print("Sound file not found")
        }
    }

    func playSound() {
        AudioServicesPlaySystemSound(soundID)
    }
}
  1. Add Sound Files to Your App Bundle

    • Open Xcode and select your project.
    • Go to File > Add Files to "{Project Name}"...
    • Select your sound file (MP3 format only).
    • Click Finish in the popup dialog.
  2. Integrate with Your View Controller

    • Add the following method to MainViewController.swift to handle sound playback:
swift
// Function to play a sound from the app bundle
@objc func playSound(_ params: [String: String]) {
    if let soundFile = params["sound"] {
        let soundHandler = SoundHandler(soundFileName: soundFile, soundFileType: "mp3")
        soundHandler.playSound()
    }
}
  1. Trigger Sound Playback in JavaScript
    • To play a sound from JavaScript, call the native playSound method:
javascript
enClose({
    nativeCall: 'playSound',
    data: {
        sound: 'click'
    }
});

WARNING

Do not include the .mp3 extension in the JavaScript call, as the native method automatically appends it.

This setup ensures smooth integration of sound effects into your app with minimal effort.