与 SwiftUI/AVPlayer 中的通知中心/组合作斗争

atd*_*nsm 3 avplayer notificationcenter swift swiftui combine

我试图在项目播放完毕后暂停我的 AVPlayer。使用 SwiftUI 执行此操作的最佳方法是什么?我对通知、在哪里声明它们等不太了解。有没有办法使用组合来实现这一点?示例代码会很棒!先感谢您。

更新:

在下面答案的帮助下,我成功创建了一个类,该类采用 AVPlayer 并在项目结束时发布通知。您可以通过以下方式订阅通知:

班级:

import Combine
import AVFoundation

class PlayerFinishedObserver {

    let publisher = PassthroughSubject<Void, Never>()

    init(player: AVPlayer) {
        let item = player.currentItem

        var cancellable: AnyCancellable?
        cancellable = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: item).sink { [weak self] change in
            self?.publisher.send()
            print("Gotcha")
            cancellable?.cancel()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

添加到您的结构中:

let finishedObserver: PlayerFinishedObserver
Run Code Online (Sandbox Code Playgroud)

订阅某些视图:

.onReceive(finishedObserver.publisher) {
                print("Gotcha!")
            }
Run Code Online (Sandbox Code Playgroud)

Але*_*кий 5

我找到了类似问题的一种解决方案:

  1. 我创建了新的子类AVPlayer
  2. 添加观察者到currentItem
  3. 重写 func observeValue,当玩家到达结束时间时添加当前项目的观察者;

这是简化的示例:

import AVKit // for player
import Combine // for observing and adding as environmentObject

final class AudioPlayer: AVPlayer, ObservableObject {

    var songDidEnd = PassthroughSubject<Void, Never>() // you can use it in some View with .onReceive function

    override init() {
        super.init()
        registerObserves()
    }

    private func registerObserves() {
        self.addObserver(self, forKeyPath: "currentItem", options: [.new], context: nil)
        // example of using 
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        // currentItem could be nil in the player. I add observer to exist item
        if keyPath == "currentItem", let item = currentItem {
            NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)

            // another way, using Combine
            var cancellable: AnyCancellable?
            cancellable = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: item).sink { [weak self] _ in
                self?.songDidEnd.send()
                cancellable?.cancel()
            }
        }
        // other observers
    }

    @objc private func playerDidFinishPlaying(_ notification: Notification) {
        playNextSong() // my implementation, here you can just write: "self.pause()"
    }

}
Run Code Online (Sandbox Code Playgroud)

更新:简单的使用示例.onReceive(小心,我在没有 Playground/Xcode 的情况下编写了它,所以它可能有错误):

struct ContentView: View {

    @EnvironmentObject var audioPlayer: AudioPlayer
    @State private var someText: String = "song is playing"

    var body: some View {
        Text(someText)
            .onReceive(self.audioPlayer.songDidEnd) { // maybe you need "_ in" here
                self.handleSongDidEnd()
        }
    }

    private func handleSongDidEnd() {
        print("song did end")
        withAnimation {
            someText = "song paused"
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

关于CombineAVPlayer你可以看看我的问题,在那里你会看到一些观察播放时间的方法和使用滑块倒回时间的功能SwiftUI

我正在使用 的一个实例AudioPlayer,控制播放/暂停功能或更改currentItem(这意味着设置另一首歌曲),如下所示:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    // other staff
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let homeView = ContentView()
            .environmentObject(AudioPlayer())

        // other staff of SceneDelegate
    }
}
Run Code Online (Sandbox Code Playgroud)