我正在使用AVPlayer
播放URL
中的音频。一切正常,但是当我在不同的ViewController
中时,我不知道如何停止当前的音频播放,我不想在player.pause()
中呼叫viewWillDisappear()
,因为我想停止在特定情况下可以使用,但我仍希望在应用程序处于非活动状态时在后台播放音频。
我在Xcode应用程序设置中启用了此功能,以便在应用程序处于非活动状态时进行后台播放
第二个问题:我可以提高这堂课吗?还是可以吗?
protocol AVPlayerServiceDelegate {
func playerDidUpdateCurrentPlayingTime(_ time: CMTime)
}
class AVPlayerService {
static let instance = AVPlayerService()
private var audioPlayer: AVPlayer!
public weak var delegate: AVPlayerServiceDelegate?
func setupPlayer(forURL url: URL) {
let playerItem: AVPlayerItem = AVPlayerItem(url: url)
audioPlayer = AVPlayer(playerItem: playerItem)
audioPlayer.play()
audioPlayer.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if self.audioPlayer.currentItem?.status == .readyToPlay {
self.delegate?.playerDidUpdateCurrentPlayingTime(self.audioPlayer.currentTime())
}
}
}
var isPlaying: Bool {
return audioPlayer.isPlaying
}
var isPaused: Bool {
return audioPlayer.isPaused
}
var rate: Float {
return audioPlayer.rate
}
func seek(to time: CMTime) {
audioPlayer.seek(to: time)
}
func seekToBeginning() {
audioPlayer.seek(to: CMTimeMake(value: 0, timescale: 1))
}
func replay() {
audioPlayer.seek(to: CMTimeMake(value: 0, timescale: 1))
audioPlayer.play()
}
func pause() {
if let audioPlayer = audioPlayer {
audioPlayer.pause()
}
}
func play() {
audioPlayer.play()
}
func freshInstance() {
audioPlayer = AVPlayer()
}
var assetDuration: CMTime {
get {
return audioPlayer.currentItem!.asset.duration
}
}
}
答案 0 :(得分:2)
您需要一种与OnGUI
对象对话的机制,以便对其执行操作。
有很多解决方法。
我个人会为播放器创建一个专用的类,用于实例化它,加载音频资源,播放,暂停等。
然后,我将这个类设为单例,以便可以从任何地方访问它,或者将其注入并将其传递给将使用它的其他类。
player
从应用程序内的任何位置发送操作
class MyAudioPlayer {
static let shared = MyAudioPlayer()
private var player: AVAudioPlayer?
func load(_ url: URL) {
player = try? AVAudioPlayer(contentsOf: url)
}
func play(url: URL) {
load(url: url)
player?.play()
}
func pause() {
player?.pause()
}
func stop() {
player?.stop()
}
}
关于即使在应用未激活的情况下也要在后台播放(可能在MyAudioPlayer.shared.play(someURL)
MyAudioPlayer.shared.pause()
中)
AppDelegate