使用Swift 4更新IOS 11.2:
如果您正在使用AVPlayer播放音频文件,则还应配置MPNowPlayingInfoCenter.default()
以在锁定屏幕上显示当前播放信息。
以下代码将在屏幕上显示当前播放控件,但无法响应任何命令。
如果您还希望控件起作用,您应该查看苹果的示例项目:https://developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322
苹果的示例代码涵盖了所有内容,但我觉得有些混乱。
如果您想播放声音并在锁屏界面上显示控件,这些步骤就足够了。
重要提示:如果您不使用AVPlayer播放声音。如果您使用一些第三方库生成声音或播放声音文件,则应阅读代码内的注释。此外,如果您使用iOS模拟器11.2,则无法在锁屏界面上看到任何控件。您应该使用设备来查看其工作情况。
1- 选择项目 ->功能 ->打开后台模式 ->选中音频、AirPlay和画中画
![ios 11 background audio setting](https://istack.dev59.com/oRMLE.webp)
2- AppDelegate.swift文件应如下所示:
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
}
catch
{
print(error)
}
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!)
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()
}
旧版IOS 8.2答案:
Patrick的回答是完全正确的。
但是我要写一下我在ios 8.2中的做法:
我在我的应用程序信息属性列表(info.plist)中添加了所需的后台模式,如下所示:
![enter image description here](https://istack.dev59.com/xOTKE.webp)
并且在我的AppDelegate.h文件中添加了以下导入:
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
然后在我的AppDelegate.m文件中,我按照以下方式精确地编写了application didFinishLaunchingWithOptionsthis:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
return YES;
}
现在应用程序即使屏幕锁定也可以继续播放音乐 :)