先來介紹一下SystemSoundID:
SystemSoundID簡介
AudioToolbox.framework是一套基于C語言的框架,使用它來播放音效其本質(zhì)是將短音頻注冊(cè)到系統(tǒng)聲音服務(wù)(System Sound Service)奥额。System Sound Service是一種簡單息罗、底層的聲音播放服務(wù),但是它本身也存在著一些限制:
播放短的聲音文件(支持振動(dòng))
你可以用它來播放一個(gè)短的聲音(30秒以下)
-
這個(gè)接口不支持等級(jí),位置驹溃,循環(huán),時(shí)間的控制,同時(shí)播放功能僵娃。在同一時(shí)間,你只能播放一個(gè)聲音腋妙。
------------注意:數(shù)據(jù)必須是PCM或者IMA4格式
----------注意:音頻文件必須打包成.caf悯许、.aif、.wav中的一種(注意這是官方文檔的說法辉阶,實(shí)際測(cè)試發(fā)現(xiàn)一些.mp3也可以播放)
主要API:
創(chuàng)建對(duì)象:
OSStatus AudioServicesCreateSystemSoundID ( CFURLRef __nonnull inFileURL,SystemSoundID * __nonnull outSystemSoundID );
銷毀對(duì)象:
OSStatus AudioServicesDisposeSystemSoundID ( SystemSoundID inSystemSoundID);
播放聲音:(一共2個(gè))
帶有振動(dòng)效果的播放:
void AudioServicesPlayAlertSound ( SystemSoundID inSystemSoundID );
void AudioServicesPlaySystemSound ( SystemSoundID inSystemSoundID );
播放完成之后執(zhí)行的操作:(其中弟四個(gè)參數(shù)是一個(gè)C語言的函數(shù))
OSStatus AudioServicesAddSystemSoundCompletion ( SystemSoundIDinSystemSoundID, CFRunLoopRef __nullable inRunLoop, CFStringRef __nullableinRunLoopMode, AudioServicesSystemSoundCompletionProc __nonnullinCompletionRoutine, void * __nullable inClientData );
用法詳解:
用法詳解:
//1.獲得音效文件的全路徑
NSURL *url=[[NSBundle mainBundle] URLForResource:@"4.wav" withExtension:nil];
//2.加載音效文件先壕,創(chuàng)建音效ID(SoundID,一個(gè)ID對(duì)應(yīng)一個(gè)音效文件)
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
//把需要銷毀的音效文件的ID傳遞給它既可銷毀
//AudioServicesDisposeSystemSoundID(soundID);
// 完成播放之后執(zhí)行的soundCompleteCallback函數(shù)
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
//3.播放音效文件
//下面的兩個(gè)函數(shù)都可以用來播放音效文件,第一個(gè)函數(shù)伴隨有震動(dòng)效果
AudioServicesPlayAlertSound(soundID);
//AudioServicesPlaySystemSound(<#SystemSoundID inSystemSoundID#>)
#pragma mark - 播放完成之后執(zhí)行的函數(shù)
void soundCompleteCallback()
{
NSLog(@"播放完成");
}
AVAudioRecorder簡介 :
使用一個(gè)錄音機(jī),您可以:
錄制,直到用戶停止錄音
在一個(gè)特定的時(shí)間錄制聲音
暫停和恢復(fù)錄制
記錄獲得輸入音頻電平數(shù)據(jù),您可以使用它們來提供計(jì)量水平
說明:
在創(chuàng)建錄音機(jī)時(shí)除了指定路徑外還必須指定錄音設(shè)置信息谆甜,因?yàn)殇浺魴C(jī)必須知道錄音文件的格式垃僚、采樣率、通道數(shù)规辱、每個(gè)采樣點(diǎn)的位數(shù)等信息谆棺,但是也并不是所有的信息都必須設(shè)置,通常只需要幾個(gè)常用設(shè)置罕袋。關(guān)于錄音設(shè)置詳見幫助文檔中的“AV Foundation Audio Settings Constants”改淑。
————注意:錄音的時(shí)候必須設(shè)置AVAudioSession,否則將無法錄音
/** * 設(shè)置音頻會(huì)話 */
-(void)setAudioSession{ AVAudioSession *audioSession=[AVAudioSession sharedInstance];
//設(shè)置為播放和錄音狀態(tài)浴讯,以便可以在錄制完之后播放錄音
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; [audioSession setActive:YES error:nil]; }
主要API:
初始化:
- (instancetype nullable)initWithURL:(NSURL * nonnull)url settings:(NSDictionary<NSString *,id> * nonnull)settings error:(NSError * nullable * nullable)outError
是否準(zhǔn)備好錄音:
- (BOOL)prepareToRecord
錄音:
- (BOOL)record
暫停:
- (void)pause
停止:
- (void)stop
從一個(gè)特定的時(shí)間開始錄制:
- (BOOL)recordAtTime:(NSTimeInterval)time
錄音的設(shè)置:(特別重要)
@property(readonly) NSDictionary <NSString *,id> *settings
是否啟動(dòng)音頻測(cè)量:
//是否啟用音頻測(cè)量朵夏,默認(rèn)為NO,一旦啟用音頻測(cè)量可以通過updateMeters方法更新測(cè)量值
@property(getter=isMeteringEnabled) BOOL meteringEnabled
更新音頻測(cè)量值:
//更新音頻測(cè)量值榆纽,注意如果要更新音頻測(cè)量值必須設(shè)置meteringEnabled為YES仰猖,通過音頻測(cè)量值可以即時(shí)獲得音頻分貝等信息
- (void)updateMeters
獲取指定聲道的分貝值:
//獲得指定聲道的分貝峰值捏肢,注意如果要獲得分貝峰值必須在此之前調(diào)用updateMeters方法
- (float)peakPowerForChannel:(NSUInteger)channelNumber;
再來看一下代碼的實(shí)現(xiàn):
//
// ViewController.m
// SystemSoundle播放音頻
//
// Created by dlios on 15/12/8.
// Copyright ? 2015年 PFG. All rights reserved.
//
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong)UIButton *playerButton;
@property (nonatomic, strong)UIButton *recorderButton;
@property (nonatomic, strong)UIButton *avAudionButton;
@property (nonatomic, strong)UIImageView *imageView;
@property (nonatomic, strong)UIImageView *imageViewSound;
@property (nonatomic, strong)AVAudioRecorder *reverb;
@property (nonatomic, strong)NSMutableDictionary *recordSetting;
@property (nonatomic, strong)AVAudioPlayer *player;
@property (nonatomic, strong)NSString *path;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign)double lowPassResults;
@property (nonatomic, strong)NSArray *arrayImage;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor grayColor];
AVAudioSession *session = [[AVAudioSession alloc] init];
//設(shè)置會(huì)話的工作模式
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[self creatControl];
//設(shè)置錄音的格式
[self creatSetting];
}
- (void)creatControl
{
self.playerButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.playerButton setBackgroundColor:[UIColor colorWithRed:arc4random() % 255 / 255. green:arc4random() % 255 / 255. blue:arc4random() % 255 / 255. alpha:.6]];
[self.playerButton setFrame:CGRectMake(0, 0, 100, 40)];
[self.playerButton setCenter:CGPointMake(self.view.frame.size.width / 2, 260)];
[self.playerButton setTitleColor:[UIColor colorWithRed:arc4random() % 225 / 255. green:arc4random() % 225 / 255. blue:arc4random() % 225 / 255. alpha:1] forState:UIControlStateNormal];
[self.playerButton setTitle:@"播放音效" forState:UIControlStateNormal];
[self.playerButton addTarget:self action:@selector(player:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.playerButton];
self.recorderButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.recorderButton setBackgroundColor:[UIColor colorWithRed:arc4random() % 255 / 255. green:arc4random() % 255 / 255. blue:arc4random() % 255 / 255. alpha:.6]];
[self.recorderButton setTitle:@"按住錄音" forState:UIControlStateNormal];
[self.recorderButton setTitle:@"松開結(jié)束" forState:UIControlStateHighlighted];
[self.recorderButton setTitleColor:[UIColor colorWithRed:arc4random() % 225 / 255. green:arc4random() % 225 / 255. blue:arc4random() % 225 / 255. alpha:1] forState:UIControlStateNormal];
[self.recorderButton setFrame:CGRectMake(0, 0, 100, 40)];
[self.recorderButton setCenter:CGPointMake(self.view.frame.size.width / 2, 360)];
//按下
[self.recorderButton addTarget:self action:@selector(recorderButton:) forControlEvents:UIControlEventTouchDown];
//松開
[self.recorderButton addTarget:self action:@selector(handleStop:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.recorderButton];
self.avAudionButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.avAudionButton setBackgroundColor:[UIColor colorWithRed:arc4random() % 255 / 255. green:arc4random() % 255 / 255. blue:arc4random() % 255 / 255. alpha:.6]];
[self.avAudionButton setFrame:CGRectMake(0, 0, 100, 40)];
[self.avAudionButton setCenter:CGPointMake(self.view.frame.size.width / 2, 460)];
[self.avAudionButton setTitleColor:[UIColor colorWithRed:arc4random() % 225 / 255. green:arc4random() % 225 / 255. blue:arc4random() % 225 / 255. alpha:1] forState:UIControlStateNormal];
[self.avAudionButton setTitle:@"播放本地" forState:UIControlStateNormal];
[self.avAudionButton addTarget:self action:@selector(avAudionButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.avAudionButton];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 100, 30, 60)];
[self.imageView setImage:[UIImage imageNamed:@"RecordingBkg"]];
[self.view addSubview:self.imageView];
//音量圖片數(shù)組
self.arrayImage = @[@"RecordingSignal001",@"RecordingSignal002",@"RecordingSignal003",
@"RecordingSignal004", @"RecordingSignal005",@"RecordingSignal006",
@"RecordingSignal007",@"RecordingSignal008"];
self.imageViewSound = [[UIImageView alloc] initWithFrame:CGRectMake(60, 100, 20, 60)];
[self.view addSubview:self.imageViewSound];
}
- (void)creatSetting
{
self.recordSetting = [[NSMutableDictionary alloc]init];
//設(shè)置錄音格式 AVFormatIDKey==kAudioFormatLinearPCM
[self.recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
//設(shè)置錄音采樣率(Hz) 如:AVSampleRateKey==8000/44100/96000(影響音頻的質(zhì)量)
[self.recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
//錄音通道數(shù) 1 或 2
[self.recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
//線性采樣位數(shù) 8、16饥侵、24鸵赫、32
[self.recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//錄音的質(zhì)量
[self.recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
}
#pragma mark - 播放音效
- (void)player:(UIButton *)button
{
//1.獲得音效文件的全路徑
NSString *str = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:str];
//2.加載音效文件,創(chuàng)建音效ID(SoundID,一個(gè)ID對(duì)應(yīng)一個(gè)音效文件)
SystemSoundID soundID = 0;
//創(chuàng)建聲音文件對(duì)象
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
//3.播放音效文件(帶振動(dòng))
AudioServicesPlayAlertSound(soundID);
// 完成播放之后執(zhí)行的soundCompleteCallback函數(shù)
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
//把需要銷毀的音效文件的ID傳遞給它既可銷毀
// AudioServicesDisposeSystemSoundID(soundID);
}
#pragma mark - 播放完成之后執(zhí)行的函數(shù)
void soundCompleteCallback()
{
NSLog(@"播放完成");
}
#pragma mark - 按下方法
- (void)recorderButton:(UIButton *)button
{
self.path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"aa.aac"];
NSLog(@"%@", self.path);
self.reverb = nil;
NSError *error = nil;
self.reverb = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:self.path] settings:self.recordSetting error:&error];
//開啟音量檢查
self.reverb.meteringEnabled = YES;
if ([self.reverb prepareToRecord]) {
[self.reverb record];
self.timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
}else{
NSLog(@"錄音沒準(zhǔn)備好:%@", error);
}
}
#pragma mark - 松開方法
- (void)handleStop:(UIButton *)button
{
[self.reverb stop];
self.reverb = nil;
//銷毀定時(shí)器
[self.timer invalidate];
self.timer = nil;
//將圖片值為空
self.imageViewSound.image = [UIImage imageNamed:@""];
}
- (void)avAudionButton:(UIButton *)button
{
self.player = nil;
//創(chuàng)建播放對(duì)象
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.path] error:nil];
if ([self.player prepareToPlay]) {
[self.player play];
}else{
NSLog(@"播放器沒有準(zhǔn)備好");
}
}
#pragma mark - 定時(shí)器方法
- (void)timerClick:(NSTimer *)timer
{
//更新分值
[self.reverb updateMeters];
//call to refresh meter values刷新平均和峰值功率,此計(jì)數(shù)是以對(duì)數(shù)刻度計(jì)量的,-160表示完全安靜躏升,0表示最大輸入值
// 獲取指定聲道的分貝值:
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (0.05 * [self.reverb peakPowerForChannel:0]));
self.lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * self.lowPassResults;
if (self.lowPassResults>=0.8) {
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:7]];
}else if(self.lowPassResults>=0.7){
self.imageViewSound.image = [UIImage imageNamed:
[self.arrayImage objectAtIndex:6]];
}else if(self.lowPassResults>=0.6){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:5]];
}else if(self.lowPassResults>=0.5){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:4]];
}else if(self.lowPassResults>=0.4){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:3]];
}else if(self.lowPassResults>=0.3){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:2]];
}else if(self.lowPassResults>=0.2){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:1]];
}else if(self.lowPassResults>=0.1){
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:0]];
}else{
self.imageViewSound.image = [UIImage imageNamed:[self.arrayImage objectAtIndex:0]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end