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

如何在Swift中断后恢复音频?,第1张

概述我按照指示 here,我已经把这个测试项目放在一起来处理音频播放的中断.具体来说,我正在使用默认iphone时钟应用程序中的警报作为中断.似乎中断处理程序被调用,但没有超过let = interruptionType行,因为“错误类型”出现了两次. import UIKitimport AVFoundationclass ViewController: UIViewController { 我按照指示 here,我已经把这个测试项目放在一起来处理音频播放的中断.具体来说,我正在使用默认iphone时钟应用程序中的警报作为中断.似乎中断处理程序被调用,但没有超过let = interruptionType行,因为“错误类型”出现了两次.
import UIKitimport AVFoundationclass 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中断后恢复音频?全部内容,希望文章能够帮你解决如何在Swift中断后恢复音频?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1051314.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存