因此,我正在创建一个简单的广播电台应用。我已经编写了以下代码,并获得了播放/暂停按钮切换文本。当功能位于ViewDidLoad内部时,我只是无法确定如何访问按钮中的播放器。我确定我需要设置全局变量吗?
override func viewDidAppear(_ animated: Bool) {
guard let url = URL(string: "http://stream.radiomedia.com.au:8003/stream") else {
return
}
// Create a new AVPlayer and associate it with the player view
let player = AVPlayer(url: url)
player.allowsExternalPlayback = true
player.usesExternalPlaybackWhileExternalScreenIsActive = true
// Create a new AVPlayerViewController and pass it a reference to the player.
let playerViewController = AVPlayerViewController()
playerViewController.contentOverlayView?.backgroundColor = UIColor.white
playerViewController.view.frame = CGRect (x:100, y:100, width:200, height:200)
playerViewController.player = player
self.addChild(playerViewController)
self.view.addSubview(playerViewController.view)
playerViewController.didMove(toParent: self)
playerViewController.player = player
player.play()
}
@IBAction func playVideo(_ sender: Any) {
if(playButton == false){
playButton = true;
(sender as! UIButton).setTitle("Pause", for: [])
player.pause() // does not work
}else
{
playButton = false;
(sender as! UIButton).setTitle("Play", for: [])
player.play() // does not work
}
}
class YourVC: UIViewController {
var player = AVPlayer()
}
只需在类中声明播放器,以便其他功能可以访问它。
并且在您的viewDidApper()中,更改:
let player = AVPlayer(url: url)
to
self.player = AVPlayer(url: url)
然后您可以在班级内的任何地方调用player.pause()和player.play()。
import UIKit
import AVFoundation
class AudioPlayerVC: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wakeUp", ofType: ".mp3"))
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
@IBAction func onPressPlayPaush(_ sender: UIButton) {
if(sender == false){
sender = true
audioPlayer.pause()
}else
{
sender = false
audioPlayer.play()
}
}
使用AVAudioPlayer:
import UIKit
import AVFoundation
class AudioPlayerVC: UIViewController {
var audioPlayer:AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = try? AVAudioPlayer(contentsOf: URL(string: "http://stream.radiomedia.com.au:8003/stream")!)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}
}
@IBAction func onPressPlayPaush(_ sender: UIButton) {
audioPlayer != nil && audioPlayer!.isPlaying ? audioPlayer?.pause() : { audioPlayer?.play() }()
}
使用AVPlayer:
import UIKit
import AVFoundation
class AudioPlayerVC: UIViewController {
var audioPlayer:AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVPlayer(url: URL(string: "http://stream.radiomedia.com.au:8003/stream")!)
audioPlayer!.play()
}
}
@IBAction func onPressPlayPaush(_ sender: UIButton) {
audioPlayer!.timeControlStatus == .playing ||
audioPlayer!.timeControlStatus == .waitingToPlayAtSpecifiedRate
? audioPlayer?.pause() : { audioPlayer?.play() }()
}