首页 文章

音频无法在后台播放(iOS)

提问于
浏览
1

我试图让我的程序在后台播放重复的声音 .

在info.plist中添加

  • add(必需的背景模式)属性和(apps播放音频) .

  • 在我的故事板中,app启动了一个带有根TableViewController的UINarvigation控制器 . 在我的Root TableViewController.m中有#import .

  • 我的Root TableViewController中有一个NSTimer属性my_timer . 我在viewDidLoad方法中设置如下:

my_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doMyFunction)userInfo:nil repeats:YES];

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

我的应用程序在正面模式下会按预期定期播放声音,但永远不会在背景模式下播放 . 我无法弄清楚做错了什么,谢谢你的帮助 .

1 回答

  • 2

    playSystemSound永远不会在后台播放音频 . 要做到这一点,请在主要源代码中调用此函数,只需在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];
    

相关问题