Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone AVAudioPlayer无法在后台播放NSTimer音乐_Iphone_Ios4_Background_Nstimer_Avaudioplayer - Fatal编程技术网

Iphone AVAudioPlayer无法在后台播放NSTimer音乐

Iphone AVAudioPlayer无法在后台播放NSTimer音乐,iphone,ios4,background,nstimer,avaudioplayer,Iphone,Ios4,Background,Nstimer,Avaudioplayer,我想使用NSTimer使用AVAudioPlayer播放音乐,但[player preparetoplayer]返回否&不在后台播放 谁能给我一些建议吗 这是我的密码: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [NSTimer scheduledTimerWithTimeInterval:10 target:

我想使用NSTimer使用AVAudioPlayer播放音乐,但
[player preparetoplayer]
返回否&不在后台播放

谁能给我一些建议吗

这是我的密码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)playMusic:(NSTimer *)timer{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    NSError *error;
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if ([player prepareToPlay]) {
        [player play];
        NSLog(@"start!");
    }else{
        NSLog(@"error msg :%@",error);
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }

    UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    //        /* just fail if this happens. */
        [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
    }];
}

在开始编写代码之前。你需要告诉操作系统你想要在后台播放音乐的权限。 您可以通过在应用程序的info.plist中设置一个键来实现这一点

<key>UIBackgroundModes</key>
    <array>
            <string>audio</string>
    </array>
ui背景模式
音频

这样,当应用程序移到后台时,您将能够播放音频。

我也有同样的问题,但我从这篇文章中找到了解决方案:

#导入
#进口
AVAudioSession*audioSession=[AVAudioSession sharedInstance];
n错误*setCategoryError=nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback错误:&setCategoryError];
如果(setCategoryError){/*处理错误条件*/}
n错误*activationError=nil;
[audioSession setActive:是错误:&activationError];
如果(activationError){/*处理错误条件*/}

您需要在视图加载中执行此初始化:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test"
                                                          ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
                                                          error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
这是用于音频初始化的。这里有一个名为test的MP3,导入到项目中。 请注意,开始接收RemoteControlEvents部分非常重要。没有它,你不能从背景开始播放,只需继续听已经从前景播放的音乐

现在,您需要收听事件didEnterInBackGround(您可以使用应用程序代理的applicationidentinterbackground,但这样您就可以将代码放入它所属的类中):

现在在didEnterBG方法中:

self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES];
[self.backgroundTimer fire];
- (void)backgroundWork{
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}
出于个人原因,我每10秒重复一次这个声音,但你需要做什么就做什么。 最后,背景工作方法:

self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES];
[self.backgroundTimer fire];
- (void)backgroundWork{
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}
现在您的音频文件正在后台播放:-)


您还应该注意,您的应用程序需要具有特定的权限才能在后台继续执行作业。您需要选中“YourTarget”->功能->背景模式:音频和播放下的复选框。否则,操作系统将在几分钟后在实际情况下终止你的应用程序(没有调试器或仪器)。

但当我在应用程序中启动音乐时,它可以在后台播放。。。这让我疯狂了很长一段时间…>\u这真的很有帮助,但是如果我只想在背景模式下启动声音怎么办?因为使用[self.backgroundTimer fire]将调用backgroundWork,应用程序将播放声音井,因为在
UIApplicationIdentinterBackgroundNotification
上调用了后台工作功能,所以只有当应用程序实际进入后台模式时才会播放声音。