音频播放
添加音频所需的条件:
1,音频时间小于30秒
2,数据格式为PCM,IMA4
3,音频文件后缀 .caf .iaf .wav
引入框架
#import <AudioToolbox/AudioToolbox.h>
回调函数
void audioPlay (SystemSoundID soundID,void *clientData)
{NSLog(@"播放完成");}
获取音频路径
NSString *str=[[NSBundle mainBundle]pathForResource:@“—————“ ofType:nil];
路径转换为 NSURL
NSURL *url=[NSURL fileURLWithPath:str];
赋初始值
SystemSoundID soundID=0;
获得系统声音ID(创建)
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
播放完成的回调函数(监听播放,相当于添加事件)
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, audioPlay, NULL);
播放
AudioServicesPlaySystemSound(soundID);
音乐播放
引入框架 #import <AVFoundation/AVFoundation.h>
设置类属性 @property(nonatomic,strong)AVAudioPlayer *player;
字符串接收音乐文件路径 NSString *str=[[NSBundle mainBundle]pathForResource:@“—————“ ofType:nil];
路径转换为 NSURL类型 NSURL *url=[NSURL fileURLWithPath:str];
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
循环次数,0-不循环,-1-无限循环,1,2,3-循环的次数
_player.numberOfLoops=0;
设置音量初始值
_player.volume=4;
加到缓冲区
[_player prepareToPlay];
添加按钮控制音乐的播放
UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(20, 20, 60, 30)];
button.backgroundColor=[UIColor lightGrayColor];
[button setTitle:@"播放" forState:UIControlStateNormal];
[button addTarget:self action:@selector(played:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
按钮的点击事件中用到的方法
[_player play];