为什么以下代码在后台播放音频不起作用? [英] Why does the following code to play audio in the background not work?

查看:95
本文介绍了为什么以下代码在后台播放音频不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在退出应用程序时在后台播放音频,但以下代码似乎无法实现此目的。我可能做错了什么?

I want to play audio in the background when I quit an application, but the following code does not appear to achieve this. What might I be doing wrong?

- (void)applicationDidEnterBackground:(UIApplication *)application 
{
     printf("hello");
     UIApplication  *app = [UIApplication sharedApplication];
     //beginBackgroundTaskWithExpirationHandler *bgTask; 

     bgTask = [app beginBackgroundTaskWithExpirationHandler:^{[theAudio play]; [app 

        endBackgroundTask:bgTask]; bgTask =UIBackgroundTaskInvalid;

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Piano"ofType:@"caf"];

        theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
        [theAudio play]; 
     }];
     // Start the long-running task and return immediately.
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
     });
     // Do the work associated with the task.
     [app endBackgroundTask:bgTask]; 

     bgTask = UIBackgroundTaskInvalid;;
     NSLog(@"hello%@",bgTask);

}


推荐答案

你有错误的订单。您的代码必须如此:

You have a wrong order. Your code have to look like so:

- (void)applicationDidEnterBackground:(UIApplication *)application 
{
     printf("hello");
     UIApplication  *app = [UIApplication sharedApplication];
     //beginBackgroundTaskWithExpirationHandler *bgTask; 

     bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

// A handler to be called shortly before the application’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the application.
[theAudio pause]; 

 [app endBackgroundTask:bgTask]; 

 bgTask = UIBackgroundTaskInvalid;
 }];
 // Start the long-running task and return immediately.
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 });

 // Do the work associated with the task.


    NSString *path = [[NSBundle mainBundle] pathForResource:@"Piano"ofType:@"caf"];

    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play]; 


 [app endBackgroundTask:bgTask]; 

 bgTask = UIBackgroundTaskInvalid;
 NSLog(@"hello%@",bgTask);

}

这篇关于为什么以下代码在后台播放音频不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆