【问题标题】:Play music in the background using AVAudioplayer使用 AVAudioplayer 在后台播放音乐
【发布时间】:2011-11-29 00:09:17
【问题描述】:

即使应用程序在后台运行,我也想播放音乐。我检查了所有 stackoverflow 链接,但没有一个有效。请帮助今天需要做的事情。

我使用了以下代码:-

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach"  ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

NSError *error;
playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
playerTemp.numberOfLoops = 0;
AudioSessionSetActive(true);
[playerTemp play];

【问题讨论】:

    标签: objective-c iphone ipad avaudioplayer


    【解决方案1】:

    我通过引用iOS Application Background tasks解决了这个问题

    并在我们的应用程序的.plist 文件中进行一些更改..

    更新

    在你的控制器视图中编写这段代码确实像这样加载方法

    - (void)viewDidLoad
    {
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" 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];
        [super viewDidLoad];
    }
    

    【讨论】:

    • 我这样做了,但是当我按下主页按钮时,音乐停止播放。
    • 您在哪个设备上使用此测试
    • 你应该在那些支持后台任务的设备上测试这个
    • 不要在模拟器中测试这个。在实际的 iphone / iPad 上进行测试
    • 注意声音可以在viewDidLoad方法以外的地方播放,但是设置AVAudioSession的三行必须留在viewDidLoad方法中,不能与声音播放代码捆绑。
    【解决方案2】:

    您需要在 Info.plist 中将“音频”设置为您的 UIBackgroundModes 之一。苹果有documentation on the issue。

    【讨论】:

    • 我这样做了,但是当我按下主页按钮时,音乐停止播放。
    • 链接已修复。
    • 链接已失效(“抱歉,找不到该页面”)。
    • New link 这是本质上需要做的事情。如果您不使用这些功能,所有“远程”的东西都是次要的。
    【解决方案3】:

    您甚至可以使用 MPMoviePlayerController 播放单声道电影。如果您喜欢,请阅读这份详细的 Apple Library 技术问答:

    iOS Developer Library Technical Q&A QA1668

    【讨论】:

      【解决方案4】:

      如果即使在 plist 中将音频设置为您的 UIBackgroundModes 之一后,音频在转到后台时也会停止,请尝试将 setting 您的 application's audio session 更改为 media playback。

      以下是相关参考: https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html

      下面是代码的样子:

      NSError *activationError = nil;
      [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
      
      NSError*setCategoryError = nil;
      [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
      

      【讨论】:

      【解决方案5】:

      我只是想在 Mehul 的回答中添加注释。这一行:

      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
      

      其实很重要。我使用其他教程来启动和运行我的 AVAudioPlayer。一切正常,但如果应用程序在后台,我的音频不会启动。澄清一下,如果应用程序进入后台时它已经在播放,我的音频很好……但如果应用程序已经在后台,它就不会启动。

      添加上述代码行后,即使应用程序在后台,我的音频也会开始播放。

      【讨论】:

      • 说你们中的任何一个 (@Anurag) 知道为什么这如此重要吗?经过数小时的搜索,它也对我有用。太疯狂了,在任何音频编程指南(AVFoundation、AudioQueue 或 AudioSession)中都没有提到它。
      • +1 太棒了!我刚刚在stackoverflow.com/q/13335940/13441 询问并没有得到任何答案。只是我的应用程序看起来很难看,它删除了附加的控制按钮。
      【解决方案6】:

      如果您使用MPMusicPlayerController,这里也很重要: 您必须使用:

      [MPMusicPlayerController iPodMusicPlayer] 
      

      不是

      [MPMusicPlayerController applicationMusicPlayer] 
      

      此外,如果您不希望您的应用程序在您的应用程序启动时播放 stop music,请查看此处: AVAudioPlayer turns off iPod - how to work around?

      【讨论】:

        【解决方案7】:

        我使用下面的代码。它对我有用,并调用音频播放器实例方法的按钮单击。

        NSError *error; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]]; 
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
        [[AVAudioSession sharedInstance] setActive:YES error: &error]; 
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self.player prepareToPlay];
        

        【讨论】:

          【解决方案8】:

          来自 Apple 的示例代码:Audio Mixer (MixerHost)

          // If using a nonmixable audio session category, as this app does, you must activate reception of 
          //    remote-control events to allow reactivation of the audio session when running in the background.
          //    Also, to receive remote-control events, the app must be eligible to become the first responder.
          - (void) viewDidAppear: (BOOL) animated {
          
              [super viewDidAppear: animated];
              [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
              [self becomeFirstResponder];
          }
          

          我认为以下情况不需要远程控制事件:

          AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
                                  sizeof(value), &value);
          

          【讨论】:

            【解决方案9】:

            将此行写入 plist 以进行后台运行...

            <key>UIBackgroundModes</key>
                  <array>
                          <string>audio</string>
                  </array>
            

            把这段代码写在你想用的地方

            AVAudioPlayer*  audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
            audioPlayer.delegate = self;
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setActive: YES error: nil];
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            audioPlayer.numberOfLoops =  1;       
            [audioPlayer play];
            

            【讨论】:

              【解决方案10】:

              在后台播放音频

              第 1 步:只需在您的 info.plist 中添加一个数组

              第二步:

              - (void)applicationDidEnterBackground:(UIApplication *)application
              {
                  __block UIBackgroundTaskIdentifier task = 0;
                  task=[application beginBackgroundTaskWithExpirationHandler:^{
                      NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
                      [application endBackgroundTask:task];
                      task=UIBackgroundTaskInvalid;
                  }];
              }
              

              第三步:

              NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"iNamokar" ofType:@"mp3"];
                  NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
              
                  AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
              
                  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
                  [[AVAudioSession sharedInstance] setActive: YES error: nil];
                  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
              [player prepareToPlay];
              [self.player play];
              

              【讨论】:

              • 我有几个问题:“第 2 步”背后的想法是什么?我这一行在“步骤 3”中是强制性的 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]?
              【解决方案11】:

              第一步

              在 info.plist 中进行以下更改

              1. 应用程序不在后台运行:否

              2. 所需的背景模式

                item0 :App plays audio or streams audio/video using AirPlay

              第 2 步 不要忘记在MainViewController.h文件中添加以下内容

              1. #import &lt;'AVFoundation/AVAudioPlayer.h&gt;
              2. @interface MainViewController:&lt;'AVAudioPlayerDelegate&gt;

              3. AVAudioPlayer *H_audio_player;

              第 3 步 在 MainViewController 类的 play action 中添加以下代码。

              NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d-%d",C_CID, C_SID] ofType:@"mp3"];
              NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
              H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
              H_audio_player.delegate = self;
              H_audio_player.numberOfLoops = -1;
              

              【讨论】:

                【解决方案12】:

                从所有答案中,当用户唤醒设备时,缺少此代码来控制播放器:

                - (BOOL)canBecomeFirstResponder {
                        return YES;
                    }
                
                - (void)remoteControlReceivedWithEvent:(UIEvent *)event {
                    switch (event.subtype) {
                
                        case UIEventSubtypeRemoteControlPlay:
                
                            [_audioPlayer play];
                            break;
                
                        case UIEventSubtypeRemoteControlPause:
                
                            [_audioPlayer pause];
                            break;
                
                        default:
                            break;
                    }
                }
                

                你有所有这些选择:

                UIEventSubtypeRemoteControlPlay                 = 100,
                UIEventSubtypeRemoteControlPause                = 101,
                UIEventSubtypeRemoteControlStop                 = 102,
                UIEventSubtypeRemoteControlTogglePlayPause      = 103,
                UIEventSubtypeRemoteControlNextTrack            = 104,
                UIEventSubtypeRemoteControlPreviousTrack        = 105,
                UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
                UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
                UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
                UIEventSubtypeRemoteControlEndSeekingForward    = 109,
                

                【讨论】:

                  猜你喜欢
                  • 2011-03-26
                  • 2011-12-10
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多