草庐IT

Swift Radio Streaming AVPlayer

coder 2023-09-07 原文

我想在 Swift 中流式传输来自 Internet 的音频,但还没有找到正确的功能示例。

Objective-C

AVPlayerItem* playerItem =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:streamURL]];
[playerItem addObserver:self forKeyPath:@"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
music = [AVPlayer playerWithPlayerItem:playerItem];
[music play];

我在 Swift 中尝试什么

let playerItem = AVPlayerItem(URL:NSURL(string:url))
        var player:AVPlayer!
        player = AVPlayer(playerItem:playerItem)
        player.rate = 1.0;
        player.play()
//this is not working

我也尝试添加 playerItem.addObserver(self, forKeyPath: "timedMetadata", options: NSKeyValueObservingOptions.New, context: nil) 但我收到错误

'类 AVPlayerItem 的实例 0x16edbd20 已被释放,而键值观察者仍向其注册。当前观测信息:( 上下文:0x0,属性:0x16ea5880> )'

关于如何解决这个问题的任何想法?

最佳答案

我用 swift 创建了一个广播播放器,但我使用 MediaPlayer 框架来播放。

var radioPlayer = MPMoviePlayerController(contentURL: "YOUR NSURL OBJECT WITH YOUR CUSTOM URL TO STREAM HERE");
radioPlayer.view.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
radioPlayer.view.sizeToFit()
radioPlayer.movieSourceType = MPMovieSourceType.Streaming
radioPlayer.fullscreen = false;
radioPlayer.shouldAutoplay = true;
radioPlayer.prepareToPlay()
radioPlayer.play()
radioPlayer.controlStyle = MPMovieControlStyle.None;

如果你需要从流中监听元数据,你需要观察者这个通知 MPMoviePlayerTimedMetadataUpdatedNotification

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("metadataUpdated:"), name:MPMoviePlayerTimedMetadataUpdatedNotification, object: nil);

func metadataUpdated(n:NSNotification)
{
    if(radioPlayer.timedMetadata != nil && radioPlayer.timedMetadata.count > 0)
    {
        let firstMeta:MPTimedMetadata = radioPlayer.timedMetadata.first as! MPTimedMetadata;
        let data:String = firstMeta.value as! String;
        println(data); //your metadata here
    }
}

有了这个你就可以制作你的 radio 播放器了,因为我用这个 radio ,我制作了一个库来获取 Itunes 中的音乐信息,好吧,这个库是开放的,因为这个我只想要一个帮助,如果你发现问题,错误我们更好的解决方案,修复并推送给所有人。

ItunesSearch Lib in GitHub

关于Swift Radio Streaming AVPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075618/

有关Swift Radio Streaming AVPlayer的更多相关文章

随机推荐