当应用程序处于后台时,如何让我的AVPlayer播放?

时间:2011-01-22 22:41:52

标签: iphone ios background avplayer

我已经完成了我的作业......在这里阅读,文档,谷歌搜索,堆栈溢出......但是当用户让应用程序进入后台时,仍然没有运气使我的声音棒。

到目前为止我做了什么: 将UIBackgroundModes音频添加到plist文件中。

首先是这段代码:

radioAudio = [[AVAudioSession alloc] init];
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil];
[radioAudio setActive:YES error:nil];

然后这个:

NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u";
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain];

但是一旦用户点击主页按钮,我的声音就会消失。

我也发现了这个,但是还没有添加,但是我读过的一些东西说它不需要;

newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
     if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;

现在我不知道我应该去哪里让我的AVPlayer让用户在手机上做其他东西时收听广播。 我在带有4.2的iPhone 4上测试了这个。将其构建为4.0。

任何人都有任何建议我应该做什么?

6 个答案:

答案 0 :(得分:42)

有同样的问题,但为此找到了解决方案..

请看这里:https://devforums.apple.com/message/395049#395049

以上链接的内容:


APPNAME替换为您自己的应用名称!

我在iOS 4.2.1上

编辑:到目前为止使用iOS5 + 6 + 7测试版

UIBackgroundModes中添加APPNAME-Info.plist,选择应用播放音频

然后将AudioToolBox框架添加到文件夹框架中。

APPNAMEAppDelegate.h添加:

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

所以它看起来像这样:

...
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
...

APPNAMEAppDelegate.m中添加以下内容:

// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];

/* Pick any one of them */
// 1. Overriding the output audio route
//UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
//AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);

// 2. Changing the default output audio route
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

进入

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

但在两行之前:

[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];

构建你的项目,看看是否有任何错误,如果没有,尝试在模拟器的设备上进行调试,它可以在模拟器上出错。

希望这可以帮助其他人解决同样的问题。

答案 1 :(得分:40)

使用Swift 4更新IOS 11.2:

现在,如果您使用 AVPlayer 播放音乐文件,您还应配置MPNowPlayingInfoCenter.default()以在锁定屏幕上显示正在播放的信息。

下面的代码将显示现在在屏幕上播放控件,但它无法响应任何命令。

如果你还想让控件工作,你应该在这里查看apple的示例项目:https://developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322

Apple示例代码涵盖了所有内容,但我发现它令人困惑。

如果您想在锁定屏幕上播放声音并显示控件,这些步骤就可以了。

重要提示:如果您使用 AVPlayer 播放声音。如果您使用某些第三方库来生成声音或播放声音文件,您应该阅读代码中的注释。此外,如果您使用ios模拟器11.2,您将无法在锁定屏幕上看到任何控件。您应该使用设备查看它是否有效。


1-选择项目 - &gt;能力 - &gt;设置背景模式ON - &gt; tick Audio,AirPlay和Picture in Picture

ios 11 background audio setting

2- AppDelegate.swift 文件应如下所示:

import UIKit

import AVFoundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    {
        // Override point for customization after application launch.

        do
        {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

         //!! IMPORTANT !!
         /*
         If you're using 3rd party libraries to play sound or generate sound you should
         set sample rate manually here.
         Otherwise you wont be able to hear any sound when you lock screen
         */
            //try AVAudioSession.sharedInstance().setPreferredSampleRate(4096)
        }
        catch
        {
            print(error)
        }
        // This will enable to show nowplaying controls on lock screen
        application.beginReceivingRemoteControlEvents()

        return true
    }
}

3- ViewController.swift 应如下所示:

import UIKit

import AVFoundation
import MediaPlayer

class ViewController: UIViewController
{

    var player : AVPlayer = AVPlayer()

    override func viewDidLoad()
    {
        super.viewDidLoad()


        let path = Bundle.main.path(forResource: "music", ofType: "mp3")
        let url = URL(fileURLWithPath: path!)

        // !! IMPORTANT !!
        /*
            If you are using 3rd party libraries to play sound 
            or generate sound you should always setNowPlayingInfo 
            before you create your player object.

            right:
            self.setNowPlayingInfo()
            let notAVPlayer = SomePlayer()

            wrong(You won't be able to see any controls on lock screen.):
            let notAVPlayer = SomePlayer()
            self.setNowPlayingInfo()
         */

        self.setNowPlayingInfo()
        self.player = AVPlayer(url: url)

    }


    func setNowPlayingInfo()
    {
        let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
        var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()

        let title = "title"
        let album = "album"
        let artworkData = Data()
        let image = UIImage(data: artworkData) ?? UIImage()
        let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: {  (_) -> UIImage in
            return image
        })

        nowPlayingInfo[MPMediaItemPropertyTitle] = title
        nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album
        nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork

        nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
    }

    @IBAction func startPlayingButtonPressed(_ sender: Any)
    {
        self.player.play()
    }

OLD ANSWER IOS 8.2:

帕特里克的回答是完全正确的。

但是我要写下我为 ios 8.2 做的事情:

我添加了我的应用的info.plist 所需的背景模式 如下所示:

enter image description here

在我的 AppDelegate.h 中,我添加了这些导入:

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

然后在我的 AppDelegate.m 中,我写了应用程序didFinishLaunchingWithOptionsthis ,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    return YES;
}

即使屏幕被锁定,现在App也会继续播放音乐:)

答案 2 :(得分:10)

我已成功将音频添加到后台,方法是将以下内容添加到我的applicationDidFinishLaunching

// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];    
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

答案 3 :(得分:3)

iOS 9 Swift

您需要的只是将以下内容添加到didFinishLaunchingWithOptions

do  {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
    //TODO
}

答案 4 :(得分:1)

你有一个很好的GPS背景应用程序示例,即使在后台也能播放声音:

http://www.informit.com/articles/article.aspx?p=1646438&seqNum=5

在此示例中,使用了AudioToolbox。

我自己做了一个测试并且它有效:创建一个监视GPS帖子的简单项目(UIBackgroundModes location),每个x接收位置,使用

播放声音

AudioServicesPlaySystemSound(soundId);

然后,如果您将audio作为UIBackgroundModes的一部分,即使应用程序不再处于前台,也会播放声音。

我做了这样的测试,它运作正常!

(我没有设法让它与AVPlayer一起工作,所以我退回到AudioToolbox)

答案 5 :(得分:0)

我遇到了同样的问题,我在Apple Docs中找到了解决方案:https://developer.apple.com/library/ios/qa/qa1668/_index.html

  

问:在应用程序处于后台时,如何确保在使用AV Foundation时我的媒体能够继续播放?

     

答:您必须声明您的应用在后台播放可听内容,并为您的音频会话分配适当的类别。另请参见特殊Considerations for Video Media

相关问题