我正在尝试使用会在iPhone上触发音频警报的WatchKit应用程序。我已经设置了触发器,每5秒钟重复一次。在iPhone上,我有在后台播放短音频wav文件的逻辑。即使应用程序最小化并播放音频,它也可以正常工作。我已经在iphone上单独测试过,工作正常。
无效的步骤是手表上的触发器告诉父Iphone应用播放音频。除了2秒钟的音频警报可能被缩短了0.5秒之外,它大部分都有效。它起到了第一部分的啁啾,被切断了。每当我触发它时,它都会对整个wav声音进行剪切啁啾。
来自父应用程序的回复很好,我想知道一旦回复所有后台处理完全被切断。
我在应用程序中启用了音频的后台模式。
如何让手表触发应用在后台播放整个音频提示?
// WatchApp InterfaceController
- (void)pingIphone {
[WKInterfaceController openParentApplication:@{@"requestString":@"findphone"} reply:^(NSDictionary *replyInfo, NSError *error) {
NSLog(@"\nReply info: %@\nError: %@",replyInfo, error);
}];
}
// Iphone AppDelegate
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {
NSString * request = [userInfo objectForKey:@"requestString"];
NSDictionary * replyContent = @{@"state":(application.applicationState == UIApplicationStateBackground ? @"back" : @"not back")};
if ([request isEqualToString:@"findphone"]){
ViewController *vc = [[ViewController alloc] init];
[vc pingIphone];
}
reply(replyContent);
}
// Iphone ViewController
@property (strong, nonatomic) AVQueuePlayer *player;
- (void)viewDidLoad {
[super viewDidLoad];
// get device's default audio level on start
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
Float32 volume;
UInt32 dataSize = sizeof(Float32);
AudioSessionGetProperty (
kAudioSessionProperty_CurrentHardwareOutputVolume,
&dataSize,
&volume
);
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
}
(void)pingIphone {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if([userDefaults boolForKey:@"vibrate_bool"] == YES){
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
for(int i = 0; i < 5; i++){
[_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"alarm" withExtension:@"wav"]] afterItem:nil];
}
//NSLog(@"volume: %f",[userDefaults floatForKey:@"volume"]);
if (!(_player.rate > 0 && !_player.error)) {
[self startAudio];
}
}
- (void)startAudio {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
NSString* path = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
_player = [[AVQueuePlayer alloc] init];
for(int i = 0; i < 5; i++){
[_player insertItem:[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path]] afterItem:nil];
}
_player.volume = [userDefaults floatForKey:@"volume"];
[_player play];
if (setCategoryError)
NSLog(@"Error setting category! %@", setCategoryError);
}
答案 0 :(得分:1)
听起来你的应用程序被操作系统杀死了。请查看此答案以获取一些建议:https://stackoverflow.com/a/29848521/3704092
是的,如果您不使用后台任务,则在致电reply()
后处理结束。