简体   繁体   English

iPhone处于静音状态时如何播放声音?

[英]How to play a sound when iPhone is on silent?

I am trying to build a react-native alarm application for iOS. 我正在尝试为iOS构建本机警报应用程序。 I've had a look at a couple of libraries and the one that seemed like the best suit for my project is react-native-alarm, however I am experiencing a problem with it. 我看了几个库,似乎最适合我的项目的一个库是react-native-alarm,但是我遇到了问题。 When my device is on silent mode, the scheduled local notification that is used to wake up the device and play a sound does not do it. 当我的设备处于静音模式时,用于唤醒设备并播放声音的计划的本地通知不会执行该操作。 I saw people saying that they've tackled this issue by using AVAudioPlayer API that apple provides but I can't seem to make it work. 我看到有人说他们已经通过使用Apple提供的AVAudioPlayer API解决了这个问题,但我似乎无法使其正常工作。 A bit of guidance and help could be beneficial. 一点指导和帮助可能是有益的。

I've followed the explanation here : Play sound on iPhone even in silent mode and tried to change the code of the library in order to tackle the silent mode without luck. 我在这里按照以下说明进行操作: 即使在静音模式下也可以在iPhone上播放声音,并尝试更改库的代码以解决静音模式而没有运气。

Here's my code 这是我的代码

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^ (UNNotificationPresentationOptions))completionHandler {

    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);

    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"/Library/Ringtones/Constellation" ofType:@"m4r"];
    NSURL *url = [NSURL fileURLWithPath:soundPath];
    audioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [audioPlay play];
}

If there's something Im doing wrong or there is an alternative library that could be used in react-native I'd love to hear that. 如果我做错了什么,或者有一个可以用于本机的替代库,我很想听听。 Im not very experienced when it comes to objective-c so that's why I could have done something stupid in this piece of code. 我对Objective-C的经验不是很丰富,这就是为什么我可以在这段代码中做一些愚蠢的事情。

您忘记将会话设置为活动状态:

[[AVAudioSession sharedInstance] setActive:YES error:nil];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM