我正在为iPhone编写一个提醒应用程序,使用本地通知显示提醒。
如果在应用程序运行时提醒已关闭,则不会显示本地通知。而是在我的应用委托中调用didReceiveLocalNotification
方法,并通过显示带有提醒文本的UIAlertView
来模仿本地通知对话框。
当应用程序外部显示本地通知时,设备会振动并播放UILocalNotificationDefaultSoundName
指定的声音。同样,我想在显示UIAlertView
时在应用中模仿这个。
我可以通过调用AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
来振动设备,但我无法弄清楚如何播放本地通知默认声音。没有等效的SystemSoundID常量,我不确定路径是什么。
tl; dr 我想在显示UIAlertView时播放本地通知默认声音。有什么想法吗?
答案 0 :(得分:66)
好问题。理想情况下,有一种方法可以使用AudioServices选择系统声音。但是,Apple的“系统声音服务参考”中的以下声明暗示:
在Mac OS X中,当用户拥有时 配置系统偏好设置为闪存 警报或声音的屏幕 无法渲染,称之为 功能将导致屏幕 闪烁。在Mac OS X中,传递 不变 kSystemSoundID_UserPreferredAlert to 播放由此选择的提示音 系统偏好设置中的用户在iOS中 没有首选的用户提醒 声音。强>
由于SDK似乎很少提供,您可能希望使用自己的wav文件来模仿系统声音。在以下链接有一个很好的图书馆,也许它会有你想要的声音:http://sites.google.com/site/iphonesounds/iPhoneOriginalSystemSounds_WAV.zip
祝你好运!答案 1 :(得分:22)
您可以通过以下方式播放默认通知声音:
AudioServicesPlaySystemSound(1315);
在this link中,您可以找到可用作AudioServicesPlaySystemSound(id)参数的ID列表。
良好的编码!
答案 2 :(得分:3)
在.h文件中设置委托:
@interface ViewController : UIViewController <UIAlertViewDelegate>
{
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end
并设置上面声明的方法。
在.m文件中执行此操作:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/ma.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
[audioPlayer stop];
}
NSLog(@"U HAVE CLICKED BUTTON");
}
答案 3 :(得分:2)
这是安德鲁小答案的补充。
为了更好地模仿通知声音,您还应该配置音频会话:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
这在例如你听音乐并在此期间收到通知。
上面会话的参数与通知在后台使用应用程序触发时播放的声音相同: