我目前正在使用 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或销毁他的实例?
从这篇post我找到了在离开或开始新播放器之前完全停止AVPlayer的最佳解决方案:
videoPlayer.replaceCurrentItemWithPlayerItem(nil)
[更新] 对于 SWIFT 3:
player.replaceCurrentItem(with: nil)
2023 年注意事项。就队列播放器而言,是
qp = AVQueuePlayer()
...
qp.removeAllItems()
如果将
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")
}
}
}
SWIFT 3 版本:
player.replaceCurrentItem(with: nil)