未调用AVAudioSession.sharedInstance

时间:2017-03-25 06:53:13

标签: ios swift

我正在创建一个音频应用程序,我希望音频在屏幕关闭时继续播放。(当屏幕打开时,它在背景中运行良好。)

在xcode上启用了后台模式(我设置"音频" Info.plist中的值。)我实现了" AVAudioSession.sharedInstance"但是当我的设备中的屏幕熄灭时应用程序崩溃。有什么想法解决这个问题吗?

这是完整的代码

var player:AVAudioPlayer!

        init(withStartingClosure block1:@escaping(_ dict:[String:Any],_ index:Int) -> Void,andStopingClosure block2:@escaping(_ index:Int) -> Void,finishedAllClosure block3:((_ finished:Bool) -> Void)? = nil) {
            self.didStartPlaying = block1
            self.didStopPlaying = block2
            self.didFinishPlaying = block3
        }
        deinit {
            self.mode = .stopped
        }
    }
    extension AudioPlayer {
        func getURL(ofAudio name:String) -> URL {
            let url = URL(string: name)!
            let nm = url.deletingPathExtension().absoluteString
            let type = url.pathExtension
            let path = Bundle.main.url(forResource: nm, withExtension: type)!
            return path
        }

        func setupPlayer(withData data:[String:Any]){
            let name = data["audio"] as! String
            var idx = self.currentIndex - 1
            if idx < -1 {
                idx = -1
            }
            print("\nCurrentIndex = \(idx),and Audio is = \(data)")
            let path = self.getURL(ofAudio: name)
            do {
                try self.setupAudioSession()
                self.player = try AVAudioPlayer(contentsOf: path)
                self.player.delegate = self
                if self.player.prepareToPlay() == true {
                    self.player.play()
                    self.didStartPlaying?(data, idx)
                }else{
                    print("----------Can't Play \(data)")
                }
            }
            catch {
                print(error.localizedDescription)
                let alert = UIAlertView(title: "Error!", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
                alert.show()
            }

         let session = AVAudioSession.sharedInstance()
    do {
        try session.setCategory(AVAudioSessionCategoryPlayback)
    } catch  {
        fatalError("error1")
    }

    do {
        try session.setActive(true)
    } catch {

        fatalError("sessionError")
    }

        }

我收到的错误。 因未捕获的异常终止应用程序&#39; NSRangeException&#39;,原因:&#39; - [UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]

func reloadCell(AtIndexPath indexPath:IndexPath,shouldStop value:Int = 0){
    //"value" is default value.
    // if it is 1. it means stop playing animation of this TableViewCell
    let cell = self.table.cellForRow(at: indexPath)
    self.configureCell(cell, atIndexPath: indexPath, shouldStop: value)

   //This is the code which get crash
    self.table.scrollToRow(at: indexPath, at: .bottom, animated: true)

}

1 个答案:

答案 0 :(得分:0)

NSRangeException。这意味着您正在调用一个单元格 - 在表视图中不存在的索引路径。