【问题标题】:How to play alarm sound continuously in background如何在后台连续播放警报声
【发布时间】:2013-12-30 07:29:33
【问题描述】:

我正在开发一个要播放警报的应用程序。一旦我收到本地通知,闹钟应该会在后台响起,当我按下按钮时应该停止。

这是我的代码

NSDate *pickerDate = [self.timePicker date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
    fromDate:pickerDate];

NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
    fromDate:pickerDate];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setHour:[timeComponents hour]];
NSLog(@"set hour component %ld",(long)[timeComponents hour]); // Notification will fire in one minute

[dateComps setMinute:[timeComponents minute]];
NSLog(@"set setMinute component %ld",(long)[timeComponents minute]);
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];

UILocalNotification *localNotification = [[UILocalNotification alloc] init]; //Create the localNotification object
[localNotification setFireDate:itemDate]; 
//Set the date when the alert will be launched using the date adding the time the user selected on the timer

[localNotification setAlertAction:@"Open"]; //The button's text that launches the application and is shown in the alert
[localNotification setAlertBody:@"Wake up"]; //Set the message in the notification from the textField's text
localNotification.soundName = UILocalNotificationDefaultSoundName;
[localNotification setHasAction: YES]; //Set that pushing the button will launch the application
[localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber]+1];
//Set the Application Icon Badge Number of the application's icon to the current Application Icon Badge Number plus 1
[localNotification setUserInfo:[NSDictionary dictionaryWithObject:@"Alarm1" forKey:@"uid"]];
if (isRepeat) {
    localNotification.repeatInterval = NSDayCalendarUnit;
}

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
//Schedule the notification with the system

使用上面的代码,声音只播放 30 秒。我希望它连续播放。找了好久都没找到。

谢谢

【问题讨论】:

  • 使用时间间隔概念
  • 您好,您可以使用 AVAudioPlayer,它可以在后台运行。
  • 你能告诉我如何做到这一点,因为一旦收到通知,音频就会自动开始播放

标签: ios iphone uilocalnotification


【解决方案1】:

这是无法做到的,这样说我的意思是当应用程序在后台时,你不能在后台播放声音,就像你在收到通知时所说的那样。苹果推送和本地通知都不支持这个,你只能为通知添加叮当声,但它不会连续播放。

如果您想在后台播放声音,只有在声音开始在前台播放而不是在后台播放时才能完成,而不是使用 AVAudioPlayer Session PlayBack 在后台继续播放。

如果您认为可以添加计时器,但计时器也不能在后台工作。

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 2018-08-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多