我想实现一个自动播放音频功能时,静音推送接收。我收到一个音频URL时,无声推送来。我想播放一个音频时,应用程序在后台通过接收无声推送。但我的问题是,我是成功地接收音频URL通过无声推送,但我不能发挥音频时,应用程序在后台模式。我使用"STKAudioPlayer“播放音频,该音频是从GitHub下载的。我正在实现下面播放音频的代码
NSString *finalUrl = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"forUrl"]];
[stkaudioPlayer play:finalUrl];
下面的代码是用来接收一个无声的推送通知的,这里我正在实现播放一个音频。
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"BACK GROUND MODE PUSH");
if([userInfo[@"aps"][@"content-available"] intValue]== 1) //it's the silent notification
{
[self saveInUserDefault];
stkaudioPlayer = [[STKAudioPlayer alloc]init]; //player initialize
//Save audio url
NSString *str= [userInfo valueForKey:@"AudioURL"];
[[NSUserDefaults standardUserDefaults]setObject:str forKey:@"forUrl"];
[[NSUserDefaults standardUserDefaults] synchronize];
// for Playing an audio
NSString *finalUrl = [NSString stringWithFormat:@"%@",str];
[stkaudioPlayer play:finalUrl];
completionHandler(UIBackgroundFetchResultNewData);
// NSLog(@"I am Here");
return;
}
else
{
NSLog(@"User ... %@",userInfo);
return;
}}
如果我的实现是错误的,所以请帮助我解决这个问题。
发布于 2017-10-03 09:10:03
转到目标->功能,->后台模式,并检查您在后台获取和远程通知上的调优吗?如果没有,那就把它们打开。
之后,在您的didReceiveRemoteNotification,中,您必须添加一个您想要播放的声音文件,只需从您的push数据中取一个声音文件的名称(您需要这样做,以使push数据也发生变化),然后这样做:-(我正在使用AVAudioPlayer)。
导入- AudioToolbox/AudioToolbox.h
@property (强的,非原子的) AVAudioPlayer *声1 property;
NSString *beep=userInfo valueForKey:@"AudioURL";
NSString *path = [NSBundle mainBundle path pathForResource:beep:@“mp3”];
NSURL *url=NSURL fileURLWithPath:path;sound1Player = [AVAudioPlayer alloc alloc initWithContentsOfURL:url错误:nil];
[AVAudioSession sharedInstance集合类别:AVAudioSessionCategoryPlayback错误:nil];
[AVAudioSession sharedInstance setActive: YES error: 0];
[UIApplication sharedApplication beginReceivingRemoteControlEvents];
sound1Player.delegate=self;
sound1Player.numberOfLoops=0;
sound1Player prepareToPlay;
sound1Player播放;
(在这里,AudioURL是您想要播放的音频文件的名称,该文件位于您的项目中)
或者,如果您只想播放一个声音,那么就不需要从push数据中获取它,只需给出名称就可以从代码中获取它。
https://stackoverflow.com/questions/46538277
复制相似问题