AVAudioPlayer 如何在页面呈现之后按需初始化

在页面中按需初始化 AVAudioPlayer

很多时候我们需要根据页面上内容的情况创建 AVAudioPlayer 对象,已达到降低无谓资源占用等目的。下面我们来看一段代码看起来正确的代码:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    
    var error: NSError?
    let player = AVAudioPlayer(data: NSData(contentsOfURL: NSURL(string: "https://dl.django.t.taobao.com/rest/1.0/file?acl=5222dc2f6b41f20dae409a7743dc04fb&cID=40001&fileIds=ytQkYL66QaOs_6tYGSRHQQAAAA8AAQIC&name=13-1.mp3&timestamp=1426953600&token=5HwHU8ZKQD-kUh3Yw11nZwAAAAAABSZcAAABw60AAAAPAAEB&uID=")!)!, fileTypeHint: "AVFileTypeMPEGLayer3", error: &error)
    if let e = error {
        println(e.debugDescription)
    } else {
        player.prepareToPlay()
        player.play()
    }
}

上面这段代码看起来毫无问题,实际运行以后也是毫无问题,不报错,就是放不出声,非常奇怪。

一步解决奇怪问题

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        var error: NSError?
        player = AVAudioPlayer(data: NSData(contentsOfURL: NSURL(string: "https://dl.django.t.taobao.com/rest/1.0/file?acl=5222dc2f6b41f20dae409a7743dc04fb&cID=40001&fileIds=ytQkYL66QaOs_6tYGSRHQQAAAA8AAQIC&name=13-1.mp3&timestamp=1426953600&token=5HwHU8ZKQD-kUh3Yw11nZwAAAAAABSZcAAABw60AAAAPAAEB&uID=")!)!, fileTypeHint: "AVFileTypeMPEGLayer3", error: &error)
        if let e = error {
            println(e.debugDescription)
        } else {
            player.prepareToPlay()
            player.play()
        }
    }
}

在此控制器类的顶部事先声明播放器对象,即可成功播放!这个方法对于播放器对象数组、字典依然有效:

var playerArray = Array<AVAudioPlayer>()
var playerDictionary = Dictionary<Int, AVAudioPlayer>()

不让对象的内存被自动回收掉即可。

 
 
 
posted @ 2015-07-23 11:29  Cheetah_yang  阅读(417)  评论(0编辑  收藏  举报