錄音
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *fullPath = [path stringByAppendingPathComponent:@"test.caf"];
NSURL *url = [NSURL URLWithString:fullPath];
NSMutableDictionary *recordSettings = [NSMutableDictionary dictionary];
//編碼格式
[recordSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
// 采樣率
[recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
// 通道數(shù)
[recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
//音頻質(zhì)量,采樣質(zhì)量
[recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
AVAudioRecorder *recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSettings error:nil];
//2. prepare to record
[recorder prepareToRecord];
//3. 開始錄音
[recorder record]; // 直接錄音, 需要手動停止
[recorder recordForDuration:5]; // 從當前執(zhí)行這行代碼開始錄音, 錄音5秒
[recorder recordAtTime:recorder.deviceCurrentTime + 2]; // 2s后錄音, 需要手動停止
[recorder recordAtTime:recorder.deviceCurrentTime + 2 forDuration:5];
播放聲音
#import <AVFoundation/AVFoundation.h>
//1. 需要播放的url
NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_17.wav" withExtension:nil];
CFURLRef urlRef = (__bridge CFURLRef)(url);
//2. 創(chuàng)建SystemSoundID
SystemSoundID soundID; //類型: typedef unsigned int UInt32;
AudioServicesCreateSystemSoundID(urlRef, &soundID);
//1. 創(chuàng)建another SystemSoundID
NSURL *url2 = [[NSBundle mainBundle]URLForResource:@"win.aac" withExtension:nil];
CFURLRef urlRef2 = (__bridge CFURLRef)url2;
SystemSoundID soundID2;
AudioServicesCreateSystemSoundID(urlRef2, &soundID2);
//3. 播放
// AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
// AudioServicesDisposeSystemSoundID(soundID);
// NSLog(@"播放over");
// });
//3. 播放完一個音頻,緊接著播放另外一個音頻
AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
//url播放完畢,釋放
AudioServicesDisposeSystemSoundID(soundID);
AudioServicesPlaySystemSoundWithCompletion(soundID2, ^{
//url2播放完畢,釋放soundID2
AudioServicesDisposeSystemSoundID(soundID2);
NSLog(@"播放2個音頻完畢");
});
});
播放本地音樂
- (AVAudioPlayer *)player{
if (!_player) {
// 1. 創(chuàng)建播放器對象
// 雖然傳遞的參數(shù)是NSURL地址, 但是只支持播放本地文件, 遠程音樂文件路徑不支持
NSURL *url = [[NSBundle mainBundle]URLForResource:@"簡單愛.mp3" withExtension:nil];
_player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//允許調(diào)整速率,此設(shè)置必須在prepareplay 之前
_player.enableRate = YES;
_player.delegate = self;
[_player prepareToPlay];
}
return _player;
}
- (IBAction)startPlay {
[self.player play];
}
- (IBAction)pause {
[self.player pause];
}
- (IBAction)stop {
[self.player stop];
//為保證下次start時,從頭播放.self.currentTime需要設(shè)置為0,因為系統(tǒng)不會重置.
self.player.currentTime = 0;
//或者清空player
self.player = nil;
}
- (IBAction)forward5Seconds {
self.player.currentTime += 5;
}
- (IBAction)back5Seconds {
self.player.currentTime -= 5;
}
- (IBAction)times2Faster {
self.player.rate = 2;
}
- (IBAction)volume:(UISlider *)sender {
//音量
self.player.volume = sender.value;
}
#pragma mark ------------------------------------------
#pragma mark AVAudioPlayerDelegate 監(jiān)聽播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
//flag 表示是否播放有錯誤
if (flag) {
NSLog(@"play completed successfully");
}
}
#pragma mark ------------------------------------------
#pragma mark 實現(xiàn)后臺播放
//注:模擬器不準確:如果不設(shè)置,在真機中,無法后臺播放
- (void)backPlay{
//1.獲取音頻會話
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//2.設(shè)置音頻播放模式
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
//3.激活音頻會話
[audioSession setActive:YES error:nil];
}
AVPlayer
異步播放
- (void)asyncPlay:(AVURLAsset *)asset{
NSArray *keys = @[@"playable", @"tracks",@"duration"];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
dispatch_async(dispatch_get_main_queue(), ^{
self.playerItem = item;
if (self.player) {
[self.player replaceCurrentItemWithPlayerItem:item];
}else{
self.player = [AVPlayer playerWithPlayerItem:item];
if ([YHIphoneTool yh_iphoneVersion:10]) {
self.player.automaticallyWaitsToMinimizeStalling = NO;
}
}
if ([self.delegate respondsToSelector:@selector(remotePlayerDidFinishAsyncLoadValues:)]) {
[self.delegate remotePlayerDidFinishAsyncLoadValues:self];
}
});
NSError *error = nil;
AVKeyValueStatus status =
[asset statusOfValueForKey:@"playable" error:&error];
switch (status) {
case AVKeyValueStatusLoaded:
// Sucessfully loaded, continue processing
YHLog(@"Sucessfully loaded");
// [self.player play];
break;
case AVKeyValueStatusFailed:
// Examine NSError pointer to determine failure
YHLog(@"fail loaded, %@", error.description);
break;
case AVKeyValueStatusCancelled:
// Loading cancelled
YHLog(@"cancel loaded");
break;
default:
// Handle all other cases
break;
}
}];
}