iOS开发-音乐播放(AVAudioPlayer)
现在的手机的基本上没有人不停音乐的,我们无法想象在一个没有声音的世界里我们会过的怎么样,国内现在的主流的主流网易云音乐,QQ音乐,酷狗,虾米,天天基本上霸占了所有的用户群体,不过并没有妨碍大家对音乐的追求,乐流算是突围成功了,据说卖给QQ啦,有兴趣的可以看下。我们做不了那么高大上的就先做个简单的,最核心的就是播放,暂停,切歌,其他的基本上围绕这个修修补补锦上添花的,比如说歌曲名称,专辑,谁听了这首歌。。。铺垫的多了,直接看效果吧,三个按钮一个进度条:

初始化按钮:
self.playButton=[[UIButton alloc]initWithFrame:CGRectMake(40, 100, 60, 30)];
[self.playButton setTitle:@"播放" forState:UIControlStateNormal];
[self.playButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.playButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
self.playButton.layer.borderColor=[UIColor blackColor].CGColor;
self.playButton.layer.borderWidth=1.0;
self.playButton.layer.cornerRadius=5.0;
[self.playButton addTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.playButton]; self.pauseButton=[[UIButton alloc]initWithFrame:CGRectMake(140, 100, 60, 30)];
[self.pauseButton setTitle:@"暂停" forState:UIControlStateNormal];
[self.pauseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.pauseButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
self.pauseButton.layer.borderColor=[UIColor blackColor].CGColor;
self.pauseButton.layer.borderWidth=1.0;
self.pauseButton.layer.cornerRadius=5.0;
[self.pauseButton addTarget:self action:@selector(pauseMusic:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.pauseButton]; self.switchButton=[[UIButton alloc]initWithFrame:CGRectMake(240, 100, 60, 30)];
[self.switchButton setTitle:@"切歌" forState:UIControlStateNormal];
[self.switchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.switchButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
self.switchButton.layer.borderColor=[UIColor blackColor].CGColor;
self.switchButton.layer.borderWidth=1.0;
self.switchButton.layer.cornerRadius=5.0;
[self.switchButton addTarget:self action:@selector(switchMusic:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.switchButton];
初始化进度条:
self.progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(40, 180, 200, 50)];
[self.view addSubview:self.progressView];
AVAudioPlayer可以看成一个简易播放器,支持多种音频格式,能够进行进度、音量、播放速度等控制,已经满足了基本需求,接下来是播放音乐的代码:
if (self.audioPlayer.isPlaying) {
[self.audioPlayer pause];
}else{
[self loadMusicByAsset:[[AVURLAsset alloc] initWithURL:[[NSBundle mainBundle] URLForResource:@"我最亲爱的" withExtension:@"mp3"] options:nil]];
[self.audioPlayer play];
}
实例化AVAudioPlayer:
-(void)loadMusicByAsset:(AVURLAsset*)avUrlAsset {
if ([[NSFileManager defaultManager] fileExistsAtPath:avUrlAsset.URL.path]){
NSError *error=nil;
self.audioPlayer= [[AVAudioPlayer alloc] initWithContentsOfURL:avUrlAsset.URL error:&error];
self.audioPlayer.delegate=self;
//准备buffer,减少播放延时的时间
[self.audioPlayer prepareToPlay];
[self.audioPlayer setVolume:1]; //设置音量大小
self.audioPlayer.numberOfLoops =0;//设置播放次数,0为播放一次,负数为循环播放
if (error) {
NSLog(@"初始化错误:%@",error.localizedDescription);
}
}
}
上面是通过AVURLAsset实例化的,还可以直接通过名称实例化:
-(void)loadMusic:(NSString*)name {
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"]; //创建音乐文件路径
if ([[NSFileManager defaultManager] fileExistsAtPath:musicFilePath]){
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
NSError *error=nil;
self.audioPlayer= [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:&error];
self.audioPlayer.delegate=self;
//准备buffer,减少播放延时的时间
[self.audioPlayer prepareToPlay];
[self.audioPlayer setVolume:1]; //设置音量大小
self.audioPlayer.numberOfLoops =0;//设置播放次数,0为播放一次,负数为循环播放
if (error) {
NSLog(@"初始化错误:%@",error.localizedDescription);
}
}
}
暂停音乐,这里为了方便单独写了一个按钮,大多数情况下,播放是暂停都是同一个按钮,仅供参考:
-(void)pauseMusic:(UIButton *)sender{
if (self.audioPlayer.isPlaying) {
[self.audioPlayer pause];
}
}
切歌就是通常大家点的上一曲下一曲,很好理解:
-(void)switchMusic:(UIButton *)sender{
[self.audioPlayer stop];
[self loadMusicByAsset:[[AVURLAsset alloc] initWithURL:[[NSBundle mainBundle] URLForResource:@"我需要一美元" withExtension:@"mp3"] options:nil]];
[self.audioPlayer play];
}
通过timer实时更新进度条:
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(changeProgress)
userInfo:nil repeats:YES];
进度更新:
-(void)changeProgress{
if (self.audioPlayer.isPlaying) {
self.progressView.progress =self.audioPlayer.currentTime/self.audioPlayer.duration;
}
}
效果如下:

音乐播放完成之后可以在AVAudioPlayerDelegate的代理方法里面根据业务场景执行自己安排:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
// [self.timer invalidate];直接销毁,之后不可用,慎重考虑
// [self.timer setFireDate:[NSDate date]]; //继续
// [self.timer setFireDate:[NSDate distantPast]];//开启
[self.timer setFireDate:[NSDate distantFuture]];//暂停
}
基本上最常用就这么多了,周末愉快~
iOS开发-音乐播放(AVAudioPlayer)的更多相关文章
- iOS开发-音乐播放
现在的各种App大行其道,其实常用也就是围绕着吃喝玩乐基本的需求,视频,音乐在智能手机出现之前更是必不可少的功能,每个手机都会有一个自带的音乐播放器,当然公众也有自己的需求所以也就造就了各种音乐播放软 ...
- iOS开发—音乐的播放
iOS开发—音乐的播放 一.简单说明 音乐播放用到一个叫做AVAudioPlayer的类,这个类可以用于播放手机本地的音乐文件. 注意: (1)该类(AVAudioPlayer)只能用于播放本地音频. ...
- Android 4.3实现类似iOS在音乐播放过程中如果有来电则音乐声音渐小铃声渐大的效果
目前Android的实现是:有来电时,音乐声音直接停止,铃声直接直接使用设置的铃声音量进行铃声播放. Android 4.3实现类似iOS在音乐播放过程中如果有来电则音乐声音渐小铃声渐大的效果. 如果 ...
- iOS开发--音乐文件播放工具类的封装(包含了音效的封装)
一.头文件 #import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> @interface ...
- iOS开发----音频播放、录音、视频播放、拍照、视频录制
随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制,还是对麦克风.摄像头的操 ...
- ios 视频音乐播放
IOS开发小技巧(视频和音乐播放).IOS视频播放代码(添加MediaPlayer.framework和#import) -(void)playMovie:(NSString *)fileName{ ...
- iOS在线音乐播放SZKAVPlayer(基于AVPlayer的封装)
由于最近闲着没事,想找有关在线音乐播放的demo学习一下,在gitHub跟code4APP上面查找了很多帖子,结果很多在线音乐都是基于AudioStream实现的,我感觉用起来不太方便.后来突然发现, ...
- iOS 调用音乐播放以及视频播放器
音乐播放 NSString *path = [[NSBundle mainBundle] pathForResource:@"预谋" ofType:@"mp3" ...
- iOS 简单音乐播放器 界面搭建
如图搭建一个音乐播放器界面,具备以下几个简单功能: 1,界面协调,整洁. 2,点击播放,控制进度条. 3.三收藏歌曲,点击收藏,心形收藏标志颜色加深. 4,左右按钮,切换歌曲图片和标题. 5,点击中间 ...
随机推荐
- webview知多少?
原生页面不会用到webview,html页面内嵌APP,才会用到webview. 一.什么是webview?WebView是手机中内置了一款高性能 webkit 内核浏览器,在 SDK 中封装的一个组 ...
- react初始化阶段
初始化阶段可以使用的函数:getDefaultProps:只调用一次,实例之间共享引用.只有在组件的第一个实例被初始化的时候,才会调用他,然后react会把这个函数的返回结果保存起来,从第二个实例开始 ...
- [POI2013]Polaryzacja
[POI2013]Polaryzacja 题目大意: 给定一棵\(n(n\le250000)\)个点的树,可以对每条边定向成一个有向图,这张有向图的可达点对数为树上有路径从\(u\)到达\(v\)的点 ...
- Codeforces Round #373 (Div. 2) C. Efim and Strange Grade 水题
C. Efim and Strange Grade 题目连接: http://codeforces.com/contest/719/problem/C Description Efim just re ...
- Codeforces Round #370 (Div. 2) A. Memory and Crow 水题
A. Memory and Crow 题目连接: http://codeforces.com/contest/712/problem/A Description There are n integer ...
- 2013-2014 ACM-ICPC, NEERC, Southern Subregional Contest Problem L. Stock Trading Robot 水题
Problem L. Stock Trading Robot 题目连接: http://www.codeforces.com/gym/100253 Description CyberTrader is ...
- Windows系列之(一):Windows10 上运行Ubuntu Bash
1. 前言 2016年4月6日,Windows 10 Insider Preview 发布的版本 14316,添加了Ubuntu Bash,在Windows上提供一个Linux环境,可以直接执行Lin ...
- CentOS 7使用yum安装PHP5.6
删除旧php包 yum remove php.x86_64 php-cli.x86_64 php-common.x86_64 php-gd.x86_64 php-ldap.x86_64 php-mbs ...
- STM32F4 Timer simplified block diagram
Timers TIM1 and TIM8 use 16-bit counters and are the most complex timers of all timers included in t ...
- SimpleUpdater.NET
本类库+工具用于快速实现一个简单的自动更新程序,旨在快速简单地为现有的.Net应用程序添加上比较简单的自动更新功能. 本页包含以下内容 概述 整个自动升级工作的流程 更新包生成工具 发布更新包 为应用 ...