WatchOS4 引入了AVFoundation這款強(qiáng)大的音視頻框架疲扎。
如果你在Watch模擬器時(shí)使用AVAudioRecorder和AVAudioPlayer捷雕,你會(huì)發(fā)覺(jué)很好用。代碼如下
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Configure interface objects here.
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
// 拼接文件名
NSString *filePath = [cachePath stringByAppendingPathComponent:@"f1x.m4a"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSLog(@"data lenght: %lu",(unsigned long)data.length);
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSDictionary *settings = @{AVFormatIDKey:@(kAudioFormatMPEG4AAC),
AVSampleRateKey:@(12000),
AVNumberOfChannelsKey:@(1),
AVEncoderAudioQualityKey:@(AVAudioQualityHigh)
};
NSError *error = nil;
_recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:&error];
NSLog(@"create record error: %@",error);
_recorder.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionactive) name:@"xxx" object:nil];
}
- (IBAction)recordAction {
[_recorder record];
}
- (IBAction)playAction {
[self.player play];
}
- (IBAction)stopAction {
[_recorder stop];
}
- (AVAudioPlayer *)player {
NSError *error = nil;
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
// 拼接文件名
NSString *filePath = [cachePath stringByAppendingPathComponent:@"f1x.m4a"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSLog(@"data length: %d",data.length);
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
NSLog(@"create error: %@",error);
[_player prepareToPlay];
_player.volume = 0.9;
_player.delegate = self;
return _player;
}
但是當(dāng)你把這段代碼運(yùn)行到真機(jī)的時(shí)候,你會(huì)發(fā)現(xiàn)以下情況
1.打印的文件長(zhǎng)度是固定的
2.player播放不了棒假,沒(méi)有任何聲音
這是因?yàn)槟銢](méi)有在iphone端(不是WatchKit)的info.plist添加隱私政策“Privacy - Microphone Usage Description”
加完就好了