使用AVPlayer在ios中播放音频流

vbkedwbf  于 2023-02-26  发布在  iOS
关注(0)|答案(3)|浏览(304)

我正在尝试开发一个小应用程序,应该从一个特定的链接流音频。我正在使用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];

}
vojdkbi0

vojdkbi01#

我不知道为什么你先用一个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基金会编程指南应该是一个很好的起点,以找出如何AVPlayer的东西工作

67up9zun

67up9zun2#

这一行没有必要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];

}

另外,不要忘记将NSAlowsArbitaryLoads键添加到info.plist中

moiiocjp

moiiocjp3#

您可以使用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];

相关问题