Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Radio Streaming AVPlayer

I want to stream an audio from the Internet in Swift but haven't found a correct functional example just yet.

In Objective-C

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

What Im trying in 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

I also tried adding playerItem.addObserver(self, forKeyPath: "timedMetadata", options: NSKeyValueObservingOptions.New, context: nil) but I got an error

'An instance 0x16edbd20 of class AVPlayerItem was deallocated while key value observers were still registered with it. Current observation info: ( Context: 0x0, Property: 0x16ea5880> )'

Any ideas on how to solve this?

like image 392
danielsalare Avatar asked Nov 01 '22 16:11

danielsalare


1 Answers

I created a radio player with swift, but i used MediaPlayer framework to play.

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;

If you need listen metada from stream you need observer this notification 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
    }
}

With this you will can make your radio player, and because this radio i worked, i made one lib to get information about music in Itunes, well, this lib is open and because this I just want one favor, if you find problem, bug our better solution, fix and push to all.

ItunesSearch Lib in GitHub

like image 86
ViTUu Avatar answered Nov 18 '22 21:11

ViTUu