过去我们可以使用
Media Player框架
MPMoviePlayerController来播放视频、音频。但自
iOS9.0起,这个便被废除。取而代之的便是
AVFoundation框架的
AVPlayer。
1,AVPlayer介绍
(2)
AVPlayer既可以播放本地音频,可以播放网络音频(在线音频)。
(3)要注意的是,如果播放远程音频,
AVPlayer同样是全部加载到本地后才开始播放,而不是以流媒体的形式播放。
2,效果图
(1)下面使用
AVPlayer制作一个音乐播放器。
(2)点击按钮可以时音乐在“
播放”和“
暂停”两个状态间切换。
(4)进度条滑块可以自由拖动,并播放对应时间点的音乐。
3,样例代码
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
import
UIKit
AVFoundation
class
ViewController
:
UIViewController
{
//播放按钮
@IBOutlet
weak
var
playButton:
UIButton
!
//可拖动的进度条
playbackSlider:
UiSlider
!
//当前播放时间标签
playTime:
UILabel
!
//播放器相关
playerItem:
AVPlayerItem
?
player:
AVPlayer
?
override
func
viewDidLoad() {
super
.viewDidLoad()
//初始化播放器
playerItem =
(url: url!)
player =
AVPlayer
(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 {
//更新进度条进度值
currentTime =
(
.player!.currentTime())
.playbackSlider!.value =
Float
(currentTime)
//一个小算法,来实现00:00这种格式的播放时间
all:
Int
=
(currentTime)
m:
=all % 60
f:
(all/60)
time:
String
=
""
if
f<10{
time=
"0\(f):"
}
else
{
"\(f)"
}
m<10{
time+=
"0\(m)"
{
"\(m)"
}
//更新播放时间
.playTime!.text=time
}
}
}
//播放按钮点击
@IBAction
@H_404_639@//根据rate属性判断当天是否在播放
playButtonTapped(_ sender:
Any
) {
player?.rate == 0 {
player!.play()
playButton.setTitle(
"暂停"
,
for
: .normal)
{
player!.pause()
"播放"
: .normal)
}
}
//拖动进度条改变值时触发
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
}
viewWillDisappear(_ animated:
) {
.removeObserver(
)
}
//歌曲播放完毕
finishedPlaying(myNotification:
NSNotification
) {
print
(
"播放完毕!"
)
stopedPlayerItem:
AVPlayerItem
= myNotification.object
as
!
AVPlayerItem
stopedPlayerItem.seek(to: kCMTimeZero)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
|
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_1668.html 原文链接:https://www.f2er.com/swift/321594.html