Audio streaming in ios using AVPlayer

别说谁变了你拦得住时间么 提交于 2019-12-25 03:36:10

问题


i am trying to develop a small app which should stream audio from a particular link. I am using AVPlayer for that but i dont know why its not working. Tried google but nothing seems to be relevant there. Kindly Help.. thank you

- (void)viewDidLoad
{
[super viewDidLoad];

NSURL *url = [NSURL URLWithString:@"http://108.166.161.206:8826/stream.mp3"];

self->playerItem = [AVPlayerItem playerItemWithURL:url];
self->player = [AVPlayer playerWithPlayerItem:playerItem];
self->player = [AVPlayer playerWithURL:url];
[player play];

}

回答1:


don`t know why you first init your player with a playeritem and after that init it with an NSURL. Anyways, here is the way to go:

-(void) viewDidLoad{

    player = [[AVPlayer alloc] initWithURL:
             [NSURL URLWithString:@"http://xxx/yourfile.mp3"]];

    [player addObserver:self forKeyPath@"status" options:0 context:nil];
}

- (void) observeValueForKeyPath:(NSString *)keyPath 
                                ofObject:(id)object 
                                change:(NSDictionary  *)change 
                                context:(void *)context {

    if (object == player && [keyPath isEqualToString:@"status"]) {
        if (player.status == AVPlayerStatusReadyToPlay) {
            [player play];
        }
        if (player.status == AVPlayerStatusFailed) {
            NSLog(@"Something went wrong: %@", player.error);
        }
    }
}

The AV Foundation Programming Guide should be a good start point to find out how the AVPlayer stuff works




回答2:


You can try this with AVAudioPlayer :

NSData *fileData = [NSData dataWithContentsOfURL:
                   [NSURL URLWithString:@"http://108.166.161.206:8826/stream.mp3"]];
NSError *error = nil;
self.player = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[self.player play];


来源:https://stackoverflow.com/questions/16076128/audio-streaming-in-ios-using-avplayer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!