0

我正在尝试开发一个应该从特定链接流式传输音频的小应用程序。我为此使用 AVPlayer,但我不知道为什么它不起作用。试过谷歌,但那里似乎没有什么相关的。请帮助..谢谢

- (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];

}
4

3 回答 3

0

不知道为什么你首先用一个 playeritem 初始化你的播放器,然后用一个 NSURL 初始化它。无论如何,这是要走的路:

-(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);
        }
    }
}

AV Foundation Programming Guide应该是了解 AVPlayer 工作原理的良好起点

于 2014-02-05T20:15:00.233 回答
0

这条线不是必需的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];

}

也不要忘记将 NSAllowsArbitraryLoads 键添加到 info.plist

在此处输入图像描述

于 2020-01-24T19:23:39.520 回答
-1

你可以用 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];
于 2013-04-18T08:05:58.470 回答