【发布时间】:2015-04-28 12:58:27
【问题描述】:
我有一个计时器,当时间达到 0 时会播放声音,但现在我不明白如何触发事件以在应用程序处于后台模式或屏幕锁定时播放声音,我发现了什么在网上搜索是在我的.plist文件中设置“UIBackgroundModes”,并添加“audio”作为数组成员。
UIBackgroundModes Array
Item0 String audio
然后在应用委托中添加以下代码:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
但是声音没有播放..所以我想知道是否可以做这样的事情或者我应该改变方法
编辑:
我导入了:
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
这是我用来创建声音的代码:
AVAudioPlayer *player;
NSString *soundFilePath = [NSString stringWithFormat:@"%@/clock.mp3",
[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:nil];
player.numberOfLoops = -1;
dispatch_async(dispatch_get_main_queue(), ^{
[player prepareToPlay];
});
然后播放它:
[player play];
【问题讨论】:
-
播放声音的代码,看起来如何?您是否导入了 MediaPlayer 框架?
-
是的,很抱歉忘记了这一点:P 编辑了我的问题,这是我用来播放声音的代码,它在应用程序运行时工作正常,但如果应用程序进入后台或屏幕被锁定不'玩不了
标签: objective-c