Swift Radio Streaming AVPlayer
Asked Answered
R

1

5

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?

Rodomontade answered 27/9, 2014 at 14:21 Comment(2)
Have you consider using AVAudioPlayer?Gerhart
Are you sure the playerItem is alive after the play command? Quick thing to try is to add a sleep(10) after the play command. This will keep the thread alive for ten seconds. If you get lucky there might be some sound then.Templet
R
2

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

Rome answered 9/3, 2015 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.