WatchOS4 引入了AVFoundation这款强大的音视频框架。
如果你在Watch模拟器时使用AVAudioRecorder和AVAudioPlayer,你会发觉很好用。代码如下
- (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;
}
但是当你把这段代码运行到真机的时候,你会发现以下情况
1.打印的文件长度是固定的
2.player播放不了,没有任何声音
这是因为你没有在iphone端(不是WatchKit)的info.plist添加隐私政策“Privacy - Microphone Usage Description”
加完就好了