简体   繁体   English

ios中使用AVPlayer的音频流

[英]Audio streaming in ios using AVPlayer

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.我为此使用 AVPlayer,但我不知道为什么它不起作用。 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];

}

don`t know why you first init your player with a playeritem and after that init it with an NSURL.不知道为什么你首先用一个 playeritem 初始化你的播放器,然后用一个 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 AV Foundation Programming Guide应该是了解 AVPlayer 的工作原理的良好起点

this line isn't necessary self->player = [AVPlayer playerWithURL:url];这行不是必需的self->player = [AVPlayer playerWithURL:url];

- (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];
[player play];

}

also don't forget to add the NSAllowsArbitraryLoads key to info.plist也不要忘记将 NSAllowsArbitraryLoads 键添加到 info.plist

在此处输入图像描述

You can try this with AVAudioPlayer :你可以用 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM