Search code examples
swiftwatchkitapple-watchwatchos-simulator

Play sound on WatchOS


I'm trying to make an app for Apple Watch using Xcode. It's a very simple app that plays a sound whenever a button is played but I can't seem to find the way to play.

The audio file is in my WatchKit extension and I have tried to play it through a WKAudioFilePlayer object but I don't know if I am doing it the right way.

 override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    kickPath = Bundle.main.path(forResource:"Kick", ofType: "mp3")!
    kickUrl = URL(fileURLWithPath: kickPath!)
    kickAsset = WKAudioFileAsset(url: kickUrl!)
    kickItem = WKAudioFilePlayerItem(asset: kickAsset!)
    kick = WKAudioFilePlayer(playerItem: kickItem!)
}

@IBAction func kickButton() {
    switch kick.status {
    case .readyToPlay:
        kick.play()
        print("sound")
    case .failed:
        print("failed")
    case .unknown:
        print("unknown")
    }
}

The audio doesn't play but I know it's getting on the right switch case because it prints "sound".


Solution

  • The thing that worked for me was using AVFoundation with an AVAudioPlayer for the sound instead of the WKAudioFilePlayer I was using. It sounds through the Watch's speaker and through headphones too if you have a bluetooth set connected.