【问题标题】:Allow users background music in swift 2.0在 swift 2.0 中允许用户使用背景音乐
【发布时间】:2017-01-13 18:41:24
【问题描述】:

我正在寻找一些代码,以允许用户在仍使用我的应用程序的同时通过手机播放音乐。在 swift 2.0 之前,我会将它放在应用程序委托中,它会完美运行:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

有谁知道如何在 swift 2.0 中实现这一点?

【问题讨论】:

    标签: ios swift avfoundation swift2


    【解决方案1】:

    以下是 Swift 2 在 AVSession 上调用 setCategory 和 setActive 的语法:

    do
    {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
        try AVAudioSession.sharedInstance().setActive(true)
    }
    catch let error as NSError
    {
        print(error)
    }
    

    或

    do
    {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
    }
    catch let error as NSError
    {
        print(error)
    }
    

    【讨论】:

    • 完美运行!我还在习惯新的 swift 语法
    • 它是否适用于从 WKWebView 执行的音频?即使设备静音,它似乎也忽略了静音开关并播放声音。 forums.developer.apple.com/message/105912
    • 谢谢!!在 SO 存在之前,程序员在史前时代做了什么? ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    相关资源
    最近更新 更多