如何录制音频并使用WatchOS2进行播放?

时间:2015-06-10 09:44:58

标签: objective-c watchkit

在watchOS 2中,Apple提供了一项新功能,允许应用程序录制短音频文件,但是,如何在现有的WatchKit项目中调用这种新方法?

- (void)presentAudioRecordingControllerWithOutputURL:(NSURL * nonnull)URL
                                              preset:(WKAudioRecordingPreset)preset
                                     maximumDuration:(NSTimeInterval)maximumDuration
                                         actionTitle:(NSString * nullable)actionTitle
                                          completion:(void (^ nonnull)(BOOL didSave,
                                                               NSError * nullable error))completion;

我的问题不是如何调用该方法,是Xcode编译器说没有找到这个函数。我是否必须包含任何其他框架?可能是因为我的WatchKit项目是使用之前版本的WatchOS创建的吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

1)您需要创建一个文件URL来存储录制的输出。

NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,YES);
NSString *path = [[filePaths firstObject] stringByAppendingPathComponent:@"rec.m4a"];
NSURL *fileUrl = [NSURL fileURLWithPath:path];

您可以指定扩展名.wav,.mp4和.m4a。

2)按如下方式调用方法:

[self presentAudioRecordingControllerWithOutputURL:fileUrl
                                            preset:WKAudioRecordingPresetWideBandSpeech
                                   maximumDuration:5.0
                                       actionTitle:@"Some Title"
                                        completion:^(BOOL didSave, NSError * __nullable error) {

                                            NSLog(@"didSave:%d, error:%@", didSave, error);
                                        }];

除上述

外,您还可以选择预设
  • WKAudioRecordingPresetNarrowBandSpeech
  • WKAudioRecordingPresetHighQualityAudio

在Swift中:

self.presentAudioRecordingControllerWithOutputURL(
    self.recFileURL(),
    preset: WKAudioRecordingPreset.WideBandSpeech,
    maximumDuration: 5.0,
    actionTitle: "SomeTitle") { (didSave, error) -> Void in

        print("didSave:\(didSave), error:\(error)")
}

您可以按如下方式播放录制的文件:

self.presentMediaPlayerControllerWithURL(
    fileURL,
    options: nil) { (didPlayToEnd, endTime, error) -> Void in

        print("didPlayToEnd:\(didPlayToEnd), endTime:\(endTime), error:\(error)")
}

您可以查看详细规范here