播放音频
1.配置音频回话
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
if (![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {
NSLog(@"Category Error: %@", [error localizedDescription]);
}
if (![session setActive:YES error:&error]) {
NSLog(@"Activation Error: %@", [error localizedDescription]);
}
return YES;
}
image.png
2.播放音频
创建AVAudioPlayer
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
player.numberOfLoops = -1; // loop indefinitely
player.enableRate = YES;//指定是否为音频播放器启用播放速率调整。
[player prepareToPlay];//准备播放,会在播放时自动调用此方法。
[player play];
volume:调节声音的音量
pan:修改播放器的pan值。允许使用立方声播放声音。
rate:调整播放速率。
numberOfLoops:如果设置的值大于0,可以实现设置值的循环播放。如果设置的是-1,无限循环.
3.设置后台播放音频
在plist文件中设置添加一个新的,Required background modes类型数组,在其中添加名为App plays audio or streams audio/video using AirPlay。
4.处理中断时间
NSNotificationCenter *nsnc = [NSNotificationCenter defaultCenter];
[nsnc addObserver:self selector:@selector(handleInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
5.处理线路改变相应
NSNotificationCenter *nsnc = [NSNotificationCenter defaultCenter];
[nsnc addObserver:self
selector:@selector(handleRouteChange:)
name:AVAudioSessionRouteChangeNotification
object:[AVAudioSession sharedInstance]];
录制音频
1.设置音频会话
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
if (![session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]) {
NSLog(@"Category Error: %@", [error localizedDescription]);
}
if (![session setActive:YES error:&error]) {
NSLog(@"Activation Error: %@", [error localizedDescription]);
}
2.初始化音频录制对象。
NSString *tmpDir = NSTemporaryDirectory();
NSString *filePath = [tmpDir stringByAppendingPathComponent:@"memo.caf"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSDictionary *settings = @{
//值是CoreAudioTypes.h中的整数(格式ID)
AVFormatIDKey : @(kAudioFormatAppleIMA4),
//采样率
AVSampleRateKey : @44100.0f,
//表示为NSNumber整数值的通道数。
AVNumberOfChannelsKey : @1,
//value is an integer from 8 to 32
AVEncoderBitDepthHintKey : @16,
//音频质量
AVEncoderAudioQualityKey : @(AVAudioQualityMedium)
};
NSError *error;
self.recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:&error];
if (self.recorder) {
self.recorder.delegate = self;
self.recorder.meteringEnabled = YES;
[self.recorder prepareToRecord];
} else {
NSLog(@"Error: %@", [error localizedDescription]);
}
AVFormatIDKey:音频格式kAudioFormatMPEG4AAC是最常用的
AVSampleRateKey:采样率
AVNumberOfChannelsKey:设置2说明是立体的
- AVAudioRecorder属性
peakPowerForChannel:(NSUInteger)channelNumber:获取某声道下的峰值功率。分贝
- (float)averagePowerForChannel:(NSUInteger)channelNumber;平均分呗
网友评论