ios 使用SwiftUI获取AVPlayerItem曲目标题

ztyzrc3y  于 2022-11-26  发布在  iOS
关注(0)|答案(2)|浏览(159)

我正在尝试创建一个广播应用程序,它可以从http流媒体中播放音频。
我试图从流中获取当前播放的曲目标题,但我所能找到的都是过时的方法。
我的模型如下所示:

struct RadioStreamer {
    let streamingURL: URL

    private let player: AVPlayer?
    private let playerItem: AVPlayerItem?

    init(streamingURL: URL) {
        self.streamingURL = streamingURL

        self.playerItem = AVPlayerItem(url: self.streamingURL)
        self.player = AVPlayer(playerItem: self.playerItem)

    }

    public func playStreaming() { self.player?.play() }
}

我的contentView如下所示:

let streamer = RadioStreamer(streamingURL: URL(string: "MY-STREAMING-URL")!)

var body: some View {
    VStack {
        Text("HERE I WANT THE TRACK TITLE")

        Button(action: {
            self.streamer.playStreaming()
        }) {
            Text("Play")
        }
    }
}

如何在SwiftUI中使用一个非弃用的方法获取曲目标题?
谢谢你,谢谢你

omjgkv6w

omjgkv6w1#

这是引用类型更可取的情况。

import AVKit
import Combine

class RadioStreamer: NSObject, ObservableObject {
    @Published var itemTitle: String = "Unknown"

    let streamingURL: URL

    private let player: AVPlayer?
    private let playerItem: AVPlayerItem?

    init(streamingURL: URL) {
        self.streamingURL = streamingURL
        self.playerItem = AVPlayerItem(url: self.streamingURL)
        self.player = AVPlayer(playerItem: self.playerItem)

        super.init()

        // setup output for player item metadata
        let metaOutput = AVPlayerItemMetadataOutput(identifiers: [ // nil, for all
            // specify needed meta to be output, 
            AVMetadataIdentifier.commonIdentifierTitle.rawValue     
        ])
        metaOutput.setDelegate(self, queue: DispatchQueue.main)
        self.playerItem?.add(metaOutput)
    }

    public func playStreaming() { self.player?.play() }
}

extension RadioStreamer: AVPlayerItemMetadataOutputPushDelegate {
    func metadataOutput(_ output: AVPlayerItemMetadataOutput, didOutputTimedMetadataGroups groups: [AVTimedMetadataGroup], from track: AVPlayerItemTrack?) {

        // simplest demo, in common case iterate all groups and all items in group
        // to find what you need if you requested many metadata
        if let group = groups.first,
            let item = group.items.first {
            self.itemTitle = item.stringValue ?? "Unknown"
        }
    }
}
zbdgwd5y

zbdgwd5y2#

我遇到的问题是信息从来没有改变过。在改变了一行代码之后,魔法开始起作用了:
更改以下行:

let metaOutput = AVPlayerItemMetadataOutput(identifiers: [ // nil, for all
        // specify needed meta to be output, 
        AVMetadataIdentifier.commonIdentifierTitle.rawValue     
    ])

更改为以下行:

let metaOutput = AVPlayerItemMetadataOutput(identifiers: nil)
           metaOutput.setDelegate(self, queue: DispatchQueue.main)

相关问题