小编典典

不可能停止AVPlayer

swift

我目前正在使用 Swift
测试将AVPlayer与音频流URL一起使用。有play()pause()方法,但是问题在于,仅暂停,流仍会缓存在设备中。

这是我的测试代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let player = AVPlayer(URL: NSURL(string: "http://streaming.radio.rtl.fr/rtl-1-48-192")!)

    @IBOutlet weak var btnPlay: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()            
    }

    @IBAction func btnPress(sender: AnyObject) {
        if (btnPlay.titleLabel?.text == "Play") {
            initPlayer()
            btnPlay.setTitle("Stop", forState: UIControlState.Normal)
        } else {
            stopPlayer()
            btnPlay.setTitle("Play", forState: UIControlState.Normal)
        }
    }

    func initPlayer()  {
        player.play()
    }

    func stopPlayer() {
        // player.currentItem = nil // Last thing I tried, but generate an error
        player.pause()
    }
}

这是尝试某些东西时的问题:

player = nil :“无法将’NilLiteralCOnvertible’类型的值分配给’AVPlayer’类型的值”

player.currentItem = nil :“无法分配给属性:’currentItem’是仅获取属性”


我尝试了所有操作,即使通过AVQueuePlayer也没有任何有效结果。(显然,因为我的情况下只有一件)。

如何 停止AVPlayer销毁其实例


阅读 305

收藏
2020-07-07

共1个答案

小编典典

如果声明player为可选变量,则可以将播放器设置nil为取消分配它。

愚蠢的例子,但它显示了会发生什么:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var btnPlay: UIButton!

    var player:AVPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnPress(sender: AnyObject) {
        if (btnPlay.titleLabel?.text == "Play") {
            initPlayer()
            btnPlay.setTitle("Stop", forState: UIControlState.Normal)
        } else {
            stopPlayer()
            btnPlay.setTitle("Play", forState: UIControlState.Normal)
        }
    }

    func initPlayer()  {
        if let play = player {
            print("playing")
            play.play()
        } else {
            print("player allocated")
            player = AVPlayer(URL: NSURL(string: "http://streaming.radio.rtl.fr/rtl-1-48-192")!)
            print("playing")
            player!.play()
        }
    }

    func stopPlayer() {
        if let play = player {
            print("stopped")
            play.pause()
            player = nil
            print("player deallocated")
        } else {
            print("player was already deallocated")
        }
    }
}
2020-07-07