简使播放音频
Posted 氵如止水
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简使播放音频相关的知识,希望对你有一定的参考价值。
最近做一个项目,有一个小功能是播放音频,以前没有做过音频,于是在网上找了很多demo,但是没有想要的,然后自己去研究一个官网文档,自己也随意写了一个demo,本地播放与网络播放就是url上的差别,其他基本上一致
//本地播放
#import "LocationViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface LocationViewController ()
/* 播放器 */
@property (nonatomic, strong) AVPlayer *player;
@end
@implementation LocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 懒加载
- (AVPlayer *)player
{
if (!_player) {
//1.创建单乐资源
NSURL *url = [[NSBundle mainBundle] URLForResource:@"14945107.mp3" withExtension:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
//创建播放器
// _player = [AVPlayer playerWithURL:url]; //这个不能改变音乐的动态
_player = [AVPlayer playerWithPlayerItem:playerItem];//可以改变音乐的动态
}
return _player;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.player play];
// //切换另外一首音乐
// AVPlayerItem *nextPlayItem = [AVPlayerItem playerItemWithURL:nil];
// [self.player replaceCurrentItemWithPlayerItem:nextPlayItem];
}
//网络播放
#import "NetworkMusicViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface NetworkMusicViewController ()
/* 播放器 */
@property (nonatomic, strong) AVPlayer *player;
@end
@implementation NetworkMusicViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
- (AVPlayer *)player
{
if (!_player) {
//1.创建音乐资源
NSURL *url = [NSURL URLWithString:@"http://wvoice.spriteapp.cn/voice/2015/0824/55dafc15020d9.mp3"];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
//2.创建播放器
_player = [AVPlayer playerWithPlayerItem:playerItem];
}
return _player;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.player play];
}
以上是关于简使播放音频的主要内容,如果未能解决你的问题,请参考以下文章