Search code examples
swifthttpmp3avplayer

Get metadata from MP3 HTTP stream


I want to get the Metadata from a MP3 HTTP stream. The stream is played with AVPlayer.

I've tried it with the AVPlayerItemMetadataCollector but it returns nil.

The alternative is to get the specific part on the website of the stream where the current title is displayed.

Here is my player code:

let playerItem = AVPlayerItem(url: URL(string: "stream.p4.no/p5trondheim_mp3_hq")!)
player = AVPlayer(playerItem: playerItem)
player.rate = 1.0;
player.play()

What can I do?


Solution

  • You can observe timedMetadata on your AVPlayerItem :

    {
      ...
      // Add observer
      playerItem.addObserver(self, forKeyPath: "timedMetadata", options: .new, context: nil)
      ...
    }
    
    // Observe
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
      guard keyPath == "timedMetadata" else { return }
      guard let meta = playerItem.timedMetadata else { return }
      for metadata in meta {
        if let songName = metadata.value(forKey: "value") as? String {
          print("song name is '\(songName)'")
        }
      }
    }