最新消息:文章中包含代码时,请遵守代码高亮规范!

iOS AVPlayer播放音乐【转载】

iOS 李, 永奎 338浏览 0评论

AVPlayer不仅可以播放视频,也可以用来播放网络音乐或者本地音乐。下面叙述具体怎么使用:
一.首先要导入头文件
#import

二.初始化AVPlayer及使用
1.本地音乐文件:
– (void)initMusic{
NSString *audioPath = [[NSBundle mainBundle] pathForResource:@”yinyue” ofType:@”mp3″];
NSURL *audioUrl = [NSURL fileURLWithPath:audioPath];
AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:audioUrl];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
}

如果需要实现单曲循环播放,可以发送一个通知来处理:
– (void)initMusic{
NSString *audioPath = [[NSBundle mainBundle] pathForResource:@”yinyue” ofType:@”mp3″];
NSURL *audioUrl = [NSURL fileURLWithPath:audioPath];
AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:audioUrl];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];

//监控播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:player.currentItem];
}
– (void)playFinished{
[self initMusic];
}

2.网络音乐文件
– (void)initMusic{
AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:@”音乐文件的网址”]];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
}

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/23110.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者Future的打赏,我们会更加努力!    如果您想成为作者,请点我

您必须 登录 才能发表评论!