I am creating a very simple training application on WatchOS: one of its functions is to provide audio feedback during training. I can play the file when the display is on, but when the screen is dark, the watch does not play my file.
Can someone look through my quick code and help me figure out what I am missing?
Here is my Delegate.swift extension:
var audioPlayer = AVAudioPlayer()
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryAmbient, with: .duckOthers)
} catch {
print("audiosession cannot be set")
}
do { try audioSession.setActive(true) }
catch {
print ("audiosession cannot be activated")
}
let test = URL(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "m4a")!)
try! audioPlayer = AVAudioPlayer(contentsOf: test)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
func applicationDidBecomeActive() {
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print ("shared Instance could not be activated")
}
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task : WKRefreshBackgroundTask in backgroundTasks {
print ("received background tasks")
if task is WKApplicationRefreshBackgroundTask {
let backgroundTask : WKApplicationRefreshBackgroundTask = task as! WKApplicationRefreshBackgroundTask
backgroundTask.setTaskCompleted()
} else if task is WKSnapshotRefreshBackgroundTask {
let backgroundTask : WKSnapshotRefreshBackgroundTask = task as! WKSnapshotRefreshBackgroundTask
backgroundTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: .distantFuture, userInfo: nil)
} else if task is WKWatchConnectivityRefreshBackgroundTask {
let backgroundTask : WKWatchConnectivityRefreshBackgroundTask = task as! WKWatchConnectivityRefreshBackgroundTask
backgroundTask.setTaskCompleted()
} else if task is WKURLSessionRefreshBackgroundTask {
let backgroundTask : WKURLSessionRefreshBackgroundTask = task as! WKURLSessionRefreshBackgroundTask
backgroundTask.setTaskCompleted()
} else {
task.setTaskCompleted()
}
}
}
}
And in InterfaceController.swift I call the function:
func startTimer() {
print ("timer function started")
timer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in
print("play")
audioPlayer.play()
}
}
source
share