Sample code to play sound?

So wondering if anyone has gotten the watch to play any sounds. I've been looking for good sample code to update my old application which relied on the phone to produce the sounds. I found different examples people have been using and nothing seems to work. Currently my code looks as follows:


import WatchKit

import Foundation


var player: WKAudioFilePlayer!


class InterfaceController: WKInterfaceController {


@IBOutlet var TestButton: WKInterfaceButton!


override func awakeWithContext(context: AnyObject?) {

super.awakeWithContext(context)

// Configure interface objects here.

}


override func willActivate() {

// This method is called when watch view controller is about to be visible to user

super.willActivate()

}


override func didDeactivate() {

// This method is called when watch view controller is no longer visible

super.didDeactivate()

}




@IBAction func testPressed() {

print("test pressed")

let filePath = NSBundle.mainBundle().pathForResource("flute", ofType: "mp3")!

let fileUrl = NSURL.fileURLWithPath(filePath)

let asset = WKAudioFileAsset(URL: fileUrl)

let playerItem = WKAudioFilePlayerItem(asset: asset)

player = WKAudioFilePlayer(playerItem: playerItem)

player.play()


}



It loads on the simulator ok, but shows a bluetooth device is needed error when the button is pressed. On the watch itself, it doesn't seem to do anything. I'm working on updating my old app and have lots of sounds to use so need to figure out a good system.

I haven't tried playing sounds yet, but some thoughts come to mind:


  • Double-check that the mp3 asset can be found and is correctly loaded by the WKAudioFilePlayer
  • Check that your Watch is not muted
  • Check the error property of the WKAudioFilePlayer to find out why it is not playing audio

Adeeb,


The mp3 is used in my earlier version that worked on WK 1.0. But will double check it.


While the watch isn't muted, is there a way to check the sound levels on it? Do we have to add a sound slider on it?


That's the odd part, if I'm running it from the watch, I can't debug using Xcode. hopefully in the future they'll add that feature...so can't really check the error propertly.

My test result:


1) Needs a bluetooth speaker to play sound, if not, UI might hang (at least for my app).

2) The sound play only once, then later no sound.

Has this changed in watchkit 2? I want to play a mp3 sound on my watch.

Sample code to play sound?
 
 
Q