我正在尝试开发一个小型应用程序,它应该从特定链接传输音频。我正在使用 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];
}
不知道为什么你首先使用播放器项目初始化播放器,然后使用 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 的工作原理的一个很好的起点
这条线没有必要
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
您可以使用 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];