2013-01-20 288 views
1

我想让我的程序在后台播放反复出现的声音。音频不会在后台播放(iOS)

  1. 在info.plist中添加(需要的背景模式)属性和(应用程序播放音频)。

  2. 在我的故事板,应用程序启动一个根TableViewController一个UINarvigation控制器。在我的Root TableViewController.m中有#import。

  3. 有一个物业的NSTimer,my_timer,在我的根TableViewController。我将其设置在viewDidLoad方法如下:

my_timer = [的NSTimer scheduledTimerWithTimeInterval:1.0目标:自选择器:@selector(doMyFunction)USERINFO:无重复:YES];

  1. 在doMyFunction方法中,我有playSystemSound(1003)。

我的应用程序在前置模式下按预期定期播放声音,但从未在背景模式下播放。我无法弄清楚什么是不正确的,谢谢你的帮助。

+0

看到http://stackoverflow.com/questions/5764220/how-to-make-my -music循环重复 –

回答

2

playSystemSound绝不会在后台播放音频。要做到这一点调用这个函数在你的主源代码,只是AFER viewDidLoad中:

-(void)createAudioSession 
{ 

    // Registers this class as the delegate of the audio session. 
    [[AVAudioSession sharedInstance] setDelegate: self]; 

    // Use this code instead to allow the app sound to continue to play when the screen is locked. 
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; 

    NSError *myErr; 

    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&myErr]; 

} 

然后

AVAudioPlayer * FXPlayer; 

FXPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err]; 

FXPlayer.numberOfLoops = -1; // will loop forever 

[FXPlayer play];