音频播放#
音频播放从形式上可以分为音效播放和音乐播放,音效主要指一些短音频,通常不超过30s(格式一般为.caf, .aif, .wav)。
音效播放
#import "ViewController.h"
// 导入头文件
#import <AVFoundation/AVFoundation.h>
- (void)viewDidLoad {
[super viewDidLoad];
// 打印沙箱路径
//NSLog(@"%@",NSHomeDirectory());
[self playSoundEffect:[[NSBundle mainBundle] pathForResource:@"音效.caf" ofType:nil]];
}
-(void) playSoundEffect:(NSString *) filename{
// 通过文件路径获得文件的统一资源定位符
NSURL *fileURL = [NSURL fileURLWithPath:filename];
SystemSoundID sysSoundId;
// 调用Core Service层的函数给音效文件创建一个系统ID
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileURL), &sysSoundId);
// 通过指定系统ID来播放对应的音效文件
AudioServicesPlaySystemSound(sysSoundId);
// 播放时会产生振动
//AudioServicesPlayAlertSound(sysSoundId);
}
重复播放
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
void foo(SystemSoundID sysSoundId, void *context) {
AudioServicesPlayAlertSound(sysSoundId);
}
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filename = [[NSBundle mainBundle] pathForResource:@"音效" ofType:@"caf"];
[self playSoundEffect:filename withCallback:foo];
}
- (void) playSoundEffect:(NSString *) filename withCallback:(void (*)(SystemSoundID, void *)) callback{
// 通过文件路径获得文件的统一资源定位符
NSURL *fileURL = [NSURL fileURLWithPath:filename];
SystemSoundID sysSoundId;
// 调用Core Service层的函数给音效文件创建一个系统ID
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileURL), &sysSoundId);
// 设置音效文件播放完毕后的回调函数
// 注册在播放完之后执行的回调函数
// 第二个和第三个参数跟循环播放有关
// 第五个参数是指向传给回调函数的数据的指针
AudioServicesAddSystemSoundCompletion(sysSoundId, NULL, NULL, callback, NULL);
// 通过指定系统ID来播放对应的音效文件
AudioServicesPlaySystemSound(sysSoundId);
}
@end
音乐播放##
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
{
// 必须写成成员变量
AVAudioPlayer *myPlayer;
NSTimer *timer;
}
// 插座变量,用来显示歌曲的相关信息
@property (weak, nonatomic) IBOutlet UILabel *albumLabel;
@property (weak, nonatomic) IBOutlet UILabel *artistLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UIProgressView *playProgressView;
@property (weak, nonatomic) IBOutlet UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filename = [[NSBundle mainBundle] pathForResource:@"遇到" ofType:@"mp3"];
NSURL *fileurl = [NSURL fileURLWithPath:filename];
myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileurl error:nil];
// 设置支持后台播放
// 需要在项目中设置支持后台播放 capablities,Background Modes,Audio and AirPlay
// 获得当前音频会话对象的单例
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
// 设置应用程序支持远程控制事件(耳机控制) 需要在项目中设置 capablities,Background Modes,Ramote Notifications
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 声道切换(-1左 1右 0双声道)
myPlayer.pan = 0;
// 音量设置0~1之间(硬放大) 如果大于1就是软放大
myPlayer.volume = 1;
// 允许快进
myPlayer.enableRate = YES;
// 快进率
//myPlayer.rate = 2;
// 设置开始播放时间(单位:秒)
myPlayer.currentTime = 10;
// 绑定委托
myPlayer.delegate = self;
[myPlayer prepareToPlay];
[myPlayer play];
// 刷新界面
[self updateUI:fileurl];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progress:) userInfo:nil repeats:YES];
// 更改进度条高度
_playProgressView.transform = CGAffineTransformMakeScale(1.0f,5.0f);
}
- (void) progress:(NSTimer *) sender{
_playProgressView.progress = myPlayer.currentTime / myPlayer.duration;
}
// 视图控制器显示音乐相关信息(歌曲名、歌手、专辑、图片)
- (void) updateUI:(NSURL *) fileUrl{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileUrl options:nil];
// 根据指定的元数据格式获得对应的元数据项的数组
NSArray *metaDataItems = [asset metadataForFormat:[[asset availableMetadataFormats] firstObject]];
for (AVMetadataItem *item in metaDataItems) {
if ([item.commonKey isEqualToString:@"artist"]) {
_artistLabel.text = [item.value description];
}
else if ([item.commonKey isEqualToString:@"title"]){
_titleLabel.text = [item.value description];
}
else if ([item.commonKey isEqualToString:@"albumName"]){
_albumLabel.text = [item.value description];
}
else if ([item.commonKey isEqualToString:@"artwork"]){
_coverImageView.image = [UIImage imageWithData:(id)item.value];
}
}
}
// 播放完之后的回调方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSString *filename = [[NSBundle mainBundle] pathForResource:@"吻别" ofType:@"mp3"];
NSURL *fileurl = [NSURL fileURLWithPath:filename];
[self updateUI:fileurl];
myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileurl error:nil];
myPlayer.delegate = self;
[myPlayer prepareToPlay];
[myPlayer play];
}
// 暂停/播放按钮
- (IBAction)buttonClicked:(UIButton *)sender {
sender.selected = !sender.selected;
if(myPlayer.isPlaying){
[myPlayer pause];
[sender setTitle:@"暂停" forState:UIControlStateNormal];
timer.fireDate = [NSDate distantFuture];
}
else{
[myPlayer play];
[sender setTitle:@"播放" forState:UIControlStateNormal];
timer.fireDate = [NSDate distantPast];
}
}
- (void) dealloc{
if (timer) {
[timer invalidate];
timer = nil;
}
}
@end
录音##
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController (){
AVAudioRecorder *audioRecorder;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)buttonClicked:(UIButton *)sender {
// 录音的相关设置
NSDictionary *dict = @{
AVEncoderAudioQualityKey:@(AVAudioQualityLow),
AVEncoderBitRateKey:@(16),
AVNumberOfChannelsKey:@(2),
AVSampleRateKey:@(44100.0)
};
if (!audioRecorder) {
NSError *error = nil;
NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.caf", [self generateFilenameWithDateTime]]];
audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:filePath] settings:dict error:&error];
if (!error) {
// 准备录音
[audioRecorder prepareToRecord];
// 开始录音
[audioRecorder record];
[sender setTitle:@"停止" forState:UIControlStateNormal];
}
else {
audioRecorder = nil;
}
}
else { // 结束录音
if (audioRecorder.isRecording) {
[audioRecorder stop];
audioRecorder = nil;
}
[sender setTitle:@"录音" forState:UIControlStateNormal];
}
}
// 用日期和时间生成文件名
- (NSString *) generateFilenameWithDateTime {
// 获得当前系统的时间日期
NSDate *date = [NSDate date];
// 创建时间日期格式化器
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 指定时间日期的样式
formatter.dateFormat = @"yyyyMMddHHmmssSSS";
// 指定时区为当前系统时区
formatter.timeZone = [NSTimeZone systemTimeZone];
return [formatter stringFromDate:date];
}
@end
视频播放##
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *mpc;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test.mov" ofType:nil];
// 创建视频播放器视图控制器
mpc = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];
// 指定视图控制器视图的位置和尺寸
mpc.view.frame = self.view.bounds;
// 设置视频播放器视图控制器的视图可以自动调整宽高
mpc.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// 将视频播放器视图控制器的视图贴到当前视图控制器的视图上
[self.view addSubview:mpc.view];
// 开始播放
[mpc play];
}