iOS 5 - 在应用程序启动时在后台播放音频文件 [英] iOS 5 - play audio file in the background when the app is launched

查看:129
本文介绍了iOS 5 - 在应用程序启动时在后台播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS用户并开发应用程序。
我一直在寻找一个简单的例子,说明如何在应用程序启动时在后台播放音频文件。由于我正在开发的应用程序与音乐课程有关,因此我需要在主屏幕处于活动状态时播放此音频。这就是我到目前为止所做的...

I'm new to iOS and developing an app. I've been searching all over to get a simple example on how to play an audio file in the background when an app is launched. Since the app that I'm developing is related to music lessons, I need this audio to be playing when the home screen is active. This is what I've done so far...


  1. 创建了一个主屏幕(UIViewController),其中包含一些背景图像和一个导航按钮进一步进入应用程序。

  2. 在.plist中设置必需的背景模式

  3. 将音频文件添加到项目中

  4. 在我的控制器中,我有以下代码块。

  1. Created a home screen (UIViewController) with some background images and a button to navigate further into the app.
  2. Set up "Required background mode" in the .plist
  3. Add the audio file into the project
  4. In my controller I have the following code block.

- (void)viewDidLoad
{
    [super viewDidLoad];   

    //Set some labels here
    //Set a background image

     NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"shrutiFsharp" ofType:@"mp3"]]; 
     AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [audioPlayer play];

}


所有的标签,背景图像,按钮显示正常..我能够导航到另一个视图。但是当我在主屏幕上时,我无法播放音频文件。我正在运行iPhone 5.0模拟器。

All the labels, background image, buttons show up fine.. and I'm able to navigate to another view. But when I'm on the home screen, I just cannot get the audio file to play. I'm running the iPhone 5.0 simulator.

我在控制台中看不到任何错误消息。

I don't see any error messages in the console.

您在此处看到的代码来自已发布的示例..但我不太清楚为什么这不起作用。我可能会遗漏一些东西。任何帮助表示赞赏。

The code you see here is from an example that was already posted.. but I'm not quite sure why this does not work. I'm probably missing something dearly. Any help is appreciated.

-KD

推荐答案

你应该使用错误参数的方式。完全有可能音频播放器试图告诉你为什么它无法继续,但你忽略了它!

You should use the error parameters the way they were intended. It's entirely likely the audio player is trying to tell you exactly why it can't continue, but you're ignoring it!

NSError *error = nil;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url
                                                                    error:&error];
if (error) {
    NSLog(@"audio player error: %@", [error localizedDescription]);
}

这篇关于iOS 5 - 在应用程序启动时在后台播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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