Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Swift - 使用AVPlayer制作一个音乐播放器2(后台播放、操作、图片显示)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_772_3@概述 在前文中,我介绍了如何使用  AVFoundation 框架来制作一个简单的音频播放器( 点击查看)。但这个播放器不支持后台播放,程序退到后台时音乐就会停止播放。 本文接着介绍如何实现后台播放功能。 1,效果图 (1)运行程序并播放音乐。这时我们返回桌面或者关闭屏幕,会发现音乐仍然在播放。 (2)在锁屏界面上,会显示当前的歌曲信息、专辑图片、当前进度等。同时还提供相关的控制按钮供我们使用。 (3)
在前文中,我介绍了如何使用 AVFoundation框架来制作一个简单的音频播放器( 点击查看)。但这个播放器不支持后台播放,程序退到后台时音乐就会停止播放。
本文接着介绍如何实现后台播放功能

1,效果

(1)运行程序并播放音乐。这时我们返回桌面或者关闭屏幕,会发现音乐仍然在播放。
(2)在锁屏界面上,会显示当前的歌曲信息、专辑图片、当前进度等。同时还提供相关的控制按钮供我们使用。
(3)同样的,在上拉的音乐控制面板中,也会显示相关信息,并允许我们进行相关操作。


2,实现步骤

(1)为了让播放器能在后台持续播放,我们需要将 Targets-> Capabilities-> BACkgroundModes设为 ON,同时勾选“ Audio,AirPlay,and Picture in Picture”。

(2)同时还要在 AppDelegate.swift注册后台播放。
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
@H_673_176@@UIApplicationMain
class AppDelegate : UIResponder , UIApplicationDelegate {
var window: UIWindow ?
func application(_ application: UIApplication :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,didFinishLaunchingWithOptions
launchOptions: [ UIApplicationLaunchOptionsKey Any ]?) -> Bool {
// 注册后台播放
let session = AVAudioSession .sharedInstance()
do {
try session.setActive( true )
try session.setCategory( AVAudioSessionCategoryPlayBACk )
@H_859_262@} catch {
print (error)
}
return true
}
applicationWillResignActive(_ application: ) {
}
applicationDidEnterBACkground(_ application: UIApplication ) {
}
applicationWillEnterForeground(_ application: ) {
}
applicationDidBecomeActive(_ application: ) {
}
applicationWillTerminate(_ application: ) {
}
}

(3) ViewController.swift(主视图代码,黄色部分为新增的代码
1
2
3
13
14
15
16
17
18
19
@H_772_361@ 20
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@H_191_404@ 53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@H_696_434@ 73
74
75
76
77
78
79
80
@H_908_450@ 81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
@H_744_502@ 102
103
104
105
@H_450_499@ 106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@H_705_607@ 160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
UIKit
AVFoundation
@H_648_656@mediaPlayer
ViewController UIViewController
//播放按钮
@IBOutlet weak playButton: UIButton !
//可拖动的进度条
playBACkSlider: UiSlider !
//当前播放时间标签
playTime: UILabel !
@H_491_696@
//播放器相关
playerItem: AVPlayerItem ?
player: AVPlayer ?
override viewDidLoad() {
super .viewDidLoad()
//初始化播放器
url = URL (String: "http://mxd.766.com/sdo/music/data/3/m10.mp3" )
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)
@H_351_832@m: =all % 60
f: = Int (all/60)
time: String = ""
if f<10{
@H_772_856@time= "0\(f):"
} else {
"\(f)"
@H_262_868@} @H_465_870@m<10{
time+= "0\(m)"
{
"\(m)"
}
//更新播放时间
.playTime!.text=time
//设置后台播放显示信息
.seTinfoCenterCredentials(playBACkState: 1)
}
}
}
//播放按钮点击
@IBACtion playButtonTapped(_ sender: ) {
//根据rate属性判断当天是否在播放
player?.rate == 0 {
player!.play()
playButton.settitle( "暂停" :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, 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( :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,SELEctor: #SELEctor(finishedPlaying),
name: Nsnotification . Name . AVPlayerItemDidPlayToEndTime :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,object: playerItem)
//告诉系统接受远程响应事件,并注册成为第一响应者
.shared.beginReceivingRemoteControlEvents()
.becomeFirstResponder()
}
//页面消失时取消歌曲播放结束通知监听
viewWillDisappear(_ animated: ) {
.removeObserver( )
//停止接受远程响应事件
.shared.endReceivingRemoteControlEvents()
.resignFirstResponder()
}
//歌曲播放完毕
finishedPlaying(myNotification: Nsnotification ) {
( "播放完毕!" )
stopedPlayerItem: = myNotification.object as ! AVPlayerItem
stopedPlayerItem.seek(to: kCMTimeZero)
}
//是否能成为第一响应对象
canBecomeFirstResponder: {
true
@H_262_1089@}
// 设置后台播放显示信息
seTinfoCenterCredentials(playBACkState: ) {
@H_355_1099@mpic = @H_38_179@mPNowPlayingInfoCenter ()
//专辑封面
@H_630_1109@mySize = CGSize (width: 400,height: 400)
albumArt = @H_38_179@mPMediaItemArtwork (boundsSize:mySizE) { sz in
return UIImage (named: "cover" )!
}
//获取进度
postion = Double .playBACkSlider!.value)
duration = Double .playBACkSlider!.maximumvalue)
@H_452_1153@mpic.NowPlayingInfo = [ @H_38_179@mPMediaItemPropertytitle : "我是歌曲标题" :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, @H_909_1162@mPMediaItemPropertyArtist "hangge.com" :1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, @H_687_1168@mPMediaItemPropertyArtwork : albumArt, @H_830_1173@mPNowPlayingInfoPropertyElapsedPlayBACkTime : postion, @H_180_1177@mPMediaItemPropertyPlayBACkDuration : duration, @H_189_1181@mPNowPlayingInfoPropertyPlayBACkRate : playBACkState]
}
//后台操作
remoteControlReceived(with event: UIEvent ?) {
@H_481_1197@guard event = event {
"no event\n" )
return
}
event.type == UIEventType .remoteControl {
switch event.subtype {
case .remoteControlTogglePlayPause:
"暂停/播放" )
.remoteControlPrevIoUsTrack:
"上一首" )
.remoteControlNextTrack:
@H_777_1404@"下一首" )

大佬总结

以上是大佬教程为你收集整理的Swift - 使用AVPlayer制作一个音乐播放器2(后台播放、操作、图片显示)全部内容,希望文章能够帮你解决Swift - 使用AVPlayer制作一个音乐播放器2(后台播放、操作、图片显示)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:swift一个使用制作后台图片播放操作显示音乐
猜你在找的Swift相关文章
其他相关热搜词更多
phpJavaPython程序员load如何string使用参数jquery开发安装listlinuxiosandroid工具javascriptcap