我按照指示 here,我已经把这个测试项目放在一起来处理音频播放的中断.具体来说,我正在使用默认iphone时钟应用程序中的警报作为中断.似乎中断处理程序被调用,但没有超过let = interruptionType行,因为“错误类型”出现了两次.
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    let audioPath = NSBundle.mainBundle().pathForResource("rachmaninov-romance-sixhands-alianello",ofType: "mp3")!

    func handleInterruption(notification: NSNotification) {

        guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        switch interruptionType {

        case .Began:
            print("began")
            // player is paused and session is inactive. need to update UI)
            player.pause()
            print("audio paused")

        default:
            print("ended")
            /**/
            if let option = notification.userInfo?[AVAudioSessionInterruptionoptionKey] as? AVAudioSessionInterruptionoptions where option == .ShouldResume {
                // ok to resume playing,re activate session and resume playing
                // need to update UI
                player.play()
                print("audio resumed")
            }
            /**/
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.

        do {
            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
            player.numberOfLoops = -1 // play indefinitely
            player.preparetoPlay()
            //player.delegate = player

        } catch {
            // process error here
        }

        // enable play in background https://stackoverflow.com/a/30280699/1827488 but this audio still gets interrupted by alerts
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            print("AVAudioSession Category Playback OK")
            do {
                try AVAudioSession.sharedInstance().setActive(true)
                print("AVAudioSession is Active")
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

        // add observer to handle audio interruptions
        // using 'object: nil' does not have a noticeable effect
        let theSession = AVAudioSession.sharedInstance()
        NSNotificationCenter.defaultCenter().addobserver(self,selector: #selector(ViewController.handleInterruption(_:)),name: AVAudioSessionInterruptionNotification,object: theSession)

        // start playing audio
        player.play()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // dispose of any resources that can be recreated.
    }
}

此外,按照一个想法here,我已经修改了处理程序

func handleInterruption(notification: NSNotification) {

        //guard let interruptionType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { print("wrong type"); return }

        if notification.name != AVAudioSessionInterruptionNotification
            || notification.userInfo == nil{
            return
        }

        var info = notification.userInfo!
        var intValue: UInt = 0
        (info[AVAudioSessionInterruptionTypeKey] as! NSValue).getValue(&intValue)
        if let interruptionType = AVAudioSessionInterruptionType(rawValue: intValue) {

            switch interruptionType {

            case .Began:
                print("began")
                // player is paused and session is inactive. need to update UI)
                player.pause()
                print("audio paused")

            default:
                print("ended")
                /** /
                if let option = notification.userInfo?[AVAudioSessionInterruptionoptionKey] as? AVAudioSessionInterruptionoptions where option == .ShouldResume {
                    // ok to resume playing,re activate session and resume playing
                    // need to update UI
                    player.play()
                    print("audio resumed")
                }
                / **/
                player.play()
                print("audio resumed")
            }
        }
    }

结果是所有“开始”,“音频暂停”,“结束”和“音频恢复”都显示在控制台中,但音频播放实际上并未恢复.

注意:我将player.play()移动到注释掉的where where == .ShouldResume if语句之外,因为当发生.Ended中断时if条件不为真.

(代表OP发布).

解决方案!在讨论here后,将其插入viewDidLoad()中

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback,withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
} catch {        
}

在警报中断点击“确定”后,音频播放继续.与之前提到的不同,该解决方案不需要中断处理程序(@Leo Dabus已删除).

但是,如果您正在使用中断处理程序,则不能在handleInterruption()中调用.play(),因为这样做并不能保证播放恢复&似乎阻止调用audioPlayerEndInterruption()(见docs).相反,必须在audioPlayerEndInterruption()(其3个版本中的任何一个版本)中调用.play()以保证恢复.

此外,AVAudioSession必须提供选项.MixWithOthers @Simon Newstead注意到,如果你希望你的应用程序在你的应用程序在后台中断后恢复播放.似乎如果用户希望应用程序在进入后台时继续播放,则假设用户还希望应用程序在应用程序处于后台时中断后继续播放是合乎逻辑的.事实上,这就是Apple Music应用程序所展示的行为.

如何在Swift中断后恢复音频?的更多相关文章

  1. 如何在Swift中断后恢复音频?

    我按照指示here,我已经把这个测试项目放在一起来处理音频播放的中断.具体来说,我正在使用默认iphone时钟应用程序中的警报作为中断.似乎中断处理程序被调用,但没有超过let=interruptionType行,因为“错误类型”出现了两次.此外,按照一个想法here,我已经修改了处理程序结果是所有“开始”,“音频暂停”,“结束”和“音频恢复”都显示在控制台中,但音频播放实际上并未恢复.注意:我将

  2. Windows中的中断处理

    我想知道哪些线程处理设备中断.当用户模式线程运行时出现中断时会发生什么?本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  3. ubuntu – 高LOC中断的原因是什么?

    我看到LOC中断出现了巨大的峰值–大约每秒400万,究竟是什么会导致LOC中断,这会导致这些峰值,我该怎么办呢?

  4. 如何将单个换行符作为PHP Markdown中的实线中断处理?

    我正在读http://github.github.com/github-flavored-markdown/我想在PHPMarkdown中实现“Newline修改”:最好我想到的是:但这是非常不可预知的.在您的降价文件中查找行:并将其下面的preg模式从:至:或者你可以扩展markdown类,重新声明’doHardBreaks’功能,并将返回值改为上面的代码问候,Achmad

  5. php – MySQL中“许多连续中断的连接请求”是什么?

    我经常有以下错误:PHP致命错误:带有消息’sqlSTATE[HY000]的未捕获异常’PDOException'[1129]由于许多连接错误,主机’MYSERVER’被阻止;使用’MysqLadminflush-hosts’取消阻止使用常规MysqLadminflush-hosts命令或增加max_connect_errors系统变量很容易解决问题,如here所示.但是!什么是“许多连续中断的连接请求”,为什么会发生这种情况?

  6. Windows Server 2008,一个非常小的DDoS能够杀死我的服务器

    4个所以我有运行WindowsServer2008的i73.2Ghz6核专用服务器,网速为1Gbps.一切都运行良好,机器强大到足以处理甚至高达700Mbps的DoS攻击非常容易..没有滞后,没有问题..有时候我们习惯了大攻击,但一次只有1或2个IP,所以cpu使用率总是很好,直到最近,我们发现了一个全新的DDoS攻击!当我的服务器能够在以前的网络使用率的90%之前保持活力时,他怎么能以4%的网络使用率杀死我的服务器?!

  7. windows-xp – 什么是“中断”过程以及为什么它如此喜欢我的CPU?

    我在IntelCoreDuo2GHz上安装了WindowsXPSP3.根据ProcessExplorer,“Interrupts”进程不断占用30-40%的cpu.这是正常的吗?

  8. windows – 重新安装操作系统时软件raid是否中断?

    重新安装操作系统时,软件raid会中断吗?如果是,有没有办法防止它,或重新安装后没有数据丢失重新创建它?如果不是,那么在做这件事时你有什么需要记住的吗?还是只是自动修复?

  9. 程序集 – 使用自己的键盘中断`int 09h`处理程序时代码的奇怪行为(损坏的绘制)

    替代方案.我确实检查了如何编写DOS键盘处理程序,所以这是我的建议:…然后在游戏代码中,要检查密钥的状态,你也必须使用cs:

  10. ios – AVAudioRecorder在音频会话中断结束后不在后台录制

    int’.错误代码列在AVAudioSession.h文件中:

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部