1,效果图
(1)运行程序并播放音乐。这时我们返回桌面或者关闭屏幕,会发现音乐仍然在播放。
(3)同样的,在上拉的音乐控制面板中,也会显示相关信息,并允许我们进行相关操作。
2,实现步骤
(1)为了让播放器能在后台持续播放,我们需要将 Targets-> Capabilities-> BackgroundModes设为 ON,同时勾选“ Audio,AirPlay,and Picture in Picture”。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import
UIKit
import
AVFoundation
@UIApplicationMain
class
AppDelegate
:
UIResponder
,
UIApplicationDelegate
{
var
window:
UIWindow
?
func
application(_ application:
UIApplication
launchOptions: [
UIApplicationLaunchOptionsKey
Any
]?) ->
Bool
{
do {
try session.setActive(
true
)
try session.setCategory(
AVAudioSessionCategoryPlayback
)
} catch {
print
(error)
}
return
true
}
applicationWillResignActive(_ application:
) {
}
applicationDidEnterBackground(_ application:
UIApplication
) {
}
applicationWillEnterForeground(_ application:
) {
}
applicationDidBecomeActive(_ application:
) {
}
applicationWillTerminate(_ application:
) {
}
}
|
(3) ViewController.swift(主视图代码,黄色部分为新增的代码)
UIKit
AVFoundation
MediaPlayer
ViewController
UIViewController
//播放按钮
@IBOutlet
weak
playButton:
UIButton
!
//可拖动的进度条
playbackSlider:
UiSlider
!
//当前播放时间标签
playTime:
UILabel
!
//播放器相关
playerItem:
AVPlayerItem
?
player:
AVPlayer
?
override
viewDidLoad() {
super
.viewDidLoad()
//初始化播放器
playerItem =
AVPlayerItem
(url: url!)
player =
(playerItem: playerItem!)
//设置进度条相关属性
duration :
CMTime
= playerItem!.asset.duration
seconds :
Float64
=
CMTimeGetSeconds
(duration)
playbackSlider!.minimumValue = 0
playbackSlider!.maximumValue =
Float
(seconds)
playbackSlider!.isContinuous =
false
//播放过程中动态改变进度条值和时间标签
player!.addPeriodicTimeObserver(forInterval:
CMTimeMakeWithSeconds
(1,1),
queue:
DispatchQueue
.main) { (
) ->
Void
in
if
self
.player!.currentItem?.status == .readyToPlay &&
.player?.rate != 0{
//更新进度条进度值
currentTime =
(
.player!.currentTime())
.playbackSlider!.value =
Float
(currentTime)
//一个小算法,来实现00:00这种格式的播放时间
all:
Int
(currentTime)
m:
=all % 60
f:
=
Int
(all/60)
time:
String
=
""
if
f<10{
time=
"0\(f):"
}
else
{
"\(f)"
}
m<10{
time+=
"0\(m)"
{
"\(m)"
}
//更新播放时间
.playTime!.text=time
.setInfoCenterCredentials(playbackState: 1)
}
}
}
//播放按钮点击
@IBAction
playButtonTapped(_ sender:
) {
//根据rate属性判断当天是否在播放
player?.rate == 0 {
player!.play()
playButton.setTitle(
"暂停"
for
: .normal)
{
player!.pause()
"播放"
: .normal)
setInfoCenterCredentials(playbackState: 0)
}
}
//拖动进度条改变值时触发
playbackSliderValueChanged(_ sender:
) {
Int64
Int64
(playbackSlider.value)
targetTime:
CMTimeMake
(seconds,1)
//播放器定位到对应的位置
player!.seek(to: targetTime)
//如果当前时暂停状态,则自动播放
player!.rate == 0
{
player?.play()
: .normal)
}
}
viewWillAppear(_ animated:
Bool
) {
//播放完毕
NotificationCenter
.
default
.addObserver(
name:
NSNotification
.
Name
.
AVPlayerItemDidPlayToEndTime
//告诉系统接受远程响应事件,并注册成为第一响应者
.shared.beginReceivingRemoteControlEvents()
.becomeFirstResponder()
}
viewWillDisappear(_ animated:
) {
.removeObserver(
)
//停止接受远程响应事件
.shared.endReceivingRemoteControlEvents()
.resignFirstResponder()
}
//歌曲播放完毕
finishedPlaying(myNotification:
NSNotification
) {
(
"播放完毕!"
)
stopedPlayerItem:
= myNotification.object
as
!
AVPlayerItem
stopedPlayerItem.seek(to: kCMTimeZero)
}
//是否能成为第一响应对象
canBecomeFirstResponder:
{
true
}
setInfoCenterCredentials(playbackState:
) {
mpic =
MPNowPlayingInfoCenter
()
//专辑封面
mySize =
CGSize
(width: 400,height: 400)
albumArt =
MPMediaItemArtwork
(boundsSize:mySize) { sz
in
return
UIImage
(named:
"cover"
)!
}
//获取进度
postion =
Double
.playbackSlider!.value)
duration =
Double
.playbackSlider!.maximumValue)
mpic.nowPlayingInfo = [
MPMediaItemPropertyTitle
:
"我是歌曲标题"
MPMediaItemPropertyArtist
"hangge.com"
MPMediaItemPropertyArtwork
: albumArt,
MPNowPlayingInfoPropertyElapsedPlaybackTime
: postion,
MPMediaItemPropertyPlaybackDuration
: duration,
MPNowPlayingInfoPropertyPlaybackRate
: playbackState]
}
//后台操作
remoteControlReceived(with event:
UIEvent
?) {
guard
event = event
{
"no event\n"
)
return
}
event.type ==
UIEventType
.remoteControl {
switch
event.subtype {
case
.remoteControlTogglePlayPause:
"暂停/播放"
)
.remoteControlPrevIoUsTrack:
"上一首"
)
.remoteControlNextTrack:
@H_733_1404@"下一首"
)
.remoteControlPlay:
)
player!.play()
.remoteControlPause:
)
@H_403_1424@player!.pause()
setInfoCenterCredentials(playbackState: 0)
:
break
}
}
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
|
源码下载:
hangge_1668.zip
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_1669.html