无法阻止AVPlayer [英] Impossible to stop AVPlayer
问题描述
我目前正在使用 Swift 测试AVPlayer与音频流网址的使用情况。 播放()和 pause()方法,但问题是,仅暂停,流仍然缓存在设备中。
I am currently testing the use of AVPlayer with audio streaming url, using Swift. There are play() and pause() methods, but the problem is that, pausing only, the stream remains cached in the device.
这是我的测试代码:
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 = nil
: "Cannot assign a value of type 'NilLiteralCOnvertible' to a value of type 'AVPlayer'"
player.currentItem = nil
:无法分配给属性:'currentItem'是一个只获取属性
player.currentItem = nil
: "Cannot assign to property: 'currentItem' is a get-only property"
I尝试了一切,甚至通过 AVQueuePlayer 任何有效的结果。 (显然,因为我的情况只有一个项目。)
I tried everything, even through AVQueuePlayer without any effective result. (obviously, since I only have one item in my case).
如何停止AVPlayer 或销毁他的实例?
推荐答案
如果您将 player
声明为可选变量,然后可以将玩家设置为 nil
来解除分配。
If you declare player
as an optional variable, you can then set the player to nil
to deallocate it.
愚蠢的例子,但它显示了会发生什么:
Silly example but it shows what happens:
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")
}
}
}
这篇关于无法阻止AVPlayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!