如何在带音频反馈的WatchOS上构建Workout应用程序? [英] How to build a Workout app on WatchOS with audio feedback?

查看:150
本文介绍了如何在带音频反馈的WatchOS上构建Workout应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在WatchOS上构建一个非常简单的健身应用程序:其功能之一是在训练过程中提供音频反馈.显示屏打开时,我可以播放文件,但是当显示屏黑暗时,手表无法播放我的文件.

I am building a very simple workout app on WatchOS: One of it functions is to give audio feedback during the training. I am able to play a file when the display is on, but when the display is dark, the watch doesnt play my file.

有人可以看看我的快速代码并帮助我弄清楚我所缺少的吗?

Can some one look over my swift code and help my figuring out what I am missing?

这是我的extensionDelegate.swift:

Here is my extensionDelegate.swift:

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() {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print ("shared Instance could not be activated")
        }
    }

    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
        for task : WKRefreshBackgroundTask in backgroundTasks {
            // Check the Class of each task to decide how to process it
            print ("received background tasks")
            if task is WKApplicationRefreshBackgroundTask {
                // Be sure to complete the background task once you’re done.
                let backgroundTask : WKApplicationRefreshBackgroundTask = task as! WKApplicationRefreshBackgroundTask
                backgroundTask.setTaskCompleted()
            } else if task is WKSnapshotRefreshBackgroundTask {
                // Snapshot tasks have a unique completion call, make sure to set your expiration date
                let backgroundTask : WKSnapshotRefreshBackgroundTask = task as! WKSnapshotRefreshBackgroundTask
                backgroundTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: .distantFuture, userInfo: nil)
            } else if task is WKWatchConnectivityRefreshBackgroundTask {
                // Be sure to complete the background task once you’re done.
                let backgroundTask : WKWatchConnectivityRefreshBackgroundTask = task as! WKWatchConnectivityRefreshBackgroundTask
                backgroundTask.setTaskCompleted()
            } else if task is WKURLSessionRefreshBackgroundTask {
                // Be sure to complete the background task once you’re done.
                let backgroundTask : WKURLSessionRefreshBackgroundTask = task as! WKURLSessionRefreshBackgroundTask
                backgroundTask.setTaskCompleted()
            } else {
                // make sure to complete unhandled task types
                task.setTaskCompleted()
            }
        }
    }
}

然后在InterfaceController.swift中调用该函数:

And in InterfaceController.swift I call the function:

func startTimer() {
    // every 30 seconds
    print ("timer function started")    
    timer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { [weak self] _ in
        print("play")
        audioPlayer.play()
    }
}

推荐答案

我发现我做错了什么: 为了在不关闭屏幕的情况下播放声音,将类别设置为AVAudioSessionCategoryPlayback而不是环境非常重要.

I figured out what I did wrong: For the sound to play with the screen off, it is very important to set the category to AVAudioSessionCategoryPlayback, not ambient.

这就是我要做的所有事情:我在extensionDelegate.swift的第10行中更改了一个单词:

So that is all I did to get it working: I changed one word in line 10 of my extensionDelegate.swift:

        try audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)

这篇关于如何在带音频反馈的WatchOS上构建Workout应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆