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

swe*_*ias 29 iphone background ios avplayer

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

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

首先这段代码:

radioAudio = [[AVAudioSession alloc] init];
[radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil];
[radioAudio setActive:YES error:nil];
Run Code Online (Sandbox Code Playgroud)

然后这个:

NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u";
radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain];
Run Code Online (Sandbox Code Playgroud)

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

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

newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
     if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
        [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
bgTaskId = newTaskId;
Run Code Online (Sandbox Code Playgroud)

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

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

EFE*_*EFE 44

使用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-选择项目 - >功能 - >将背景模式设置为开 - >勾选音频,AirPlay和画中画

ios 11背景音频设置

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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()
    }
Run Code Online (Sandbox Code Playgroud)

OLD ANSWER IOS 8.2:

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

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

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

在此输入图像描述

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

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
Run Code Online (Sandbox Code Playgroud)

然后在我的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;
}
Run Code Online (Sandbox Code Playgroud)

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


Pat*_*k R 42

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

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

以上链接的内容:


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

我在iOS 4.2.1上

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

加入UIBackgroundModes,APPNAME-Info.plist选择App播放音频

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

APPNAMEAppDelegate.h添加:

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
Run Code Online (Sandbox Code Playgroud)

所以它看起来像这样:

...
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
...
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

进入

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Run Code Online (Sandbox Code Playgroud)

但在两行之前:

[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
Run Code Online (Sandbox Code Playgroud)

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

希望这有助于其他同样的问题..

  • 谢谢Patrick R!让我的背景音频工作完美!:) (2认同)

ato*_*oil 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];
Run Code Online (Sandbox Code Playgroud)


Mar*_*tes 6

iOS 9 斯威夫特

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

do  {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
    //TODO
}
Run Code Online (Sandbox Code Playgroud)