Music App

這份作業花了很多心力,從選擇音樂、畫面呈現的色調到UI安排最後是程式碼的編寫,隨著功能越來越完善就像看著自己的孩子長大一樣,我也越發有成就感,不過目前尚有我覺得不足的地方,未來打算慢慢將其補齊。

利用AVPlayer播放音樂:

func playSong() {
let playerItem = AVPlayerItem(url: songs[currentSongIndex].songUrl)
player.replaceCurrentItem(with: playerItem)
timePass = AVPlayerItem(url: songs[currentSongIndex].songUrl).asset.duration.seconds
albumCoverImageView.image = songs[currentSongIndex].albumCover
songOfTitleLabel.text = songs[currentSongIndex].songOfTitle
singerLabel.text = songs[currentSongIndex].singer
player.play()
playpauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)

let duration = CMTimeGetSeconds(playerItem.asset.duration)
songOfTimeLabel.text = timeFormatChange(time: duration)

progressBarSlider.setValue(Float(0), animated: true)
let targetTime: CMTime = CMTimeMake(value: Int64(0), timescale: 1)
player.seek(to: targetTime)

progressBarSlider.minimumValue = 0
progressBarSlider.maximumValue = Float(duration)

addProgressObserver(playerItem: playerItem)
}

上下一首的功能:

@IBAction func nextSong() {
switch playType {
case .typeDefault:
if currentSongIndex == 6 {
currentSongIndex = 0
}
else {
currentSongIndex += 1
}
playSong()
case .typeLoopOne:
if currentSongIndex == 6 {
currentSongIndex = 0
}
else {
currentSongIndex += 1
}
playSong()
case .typeRandom:
currentSongIndex = Int.random(in:0...6)
playSong()
}
}

@IBAction func previousSong() {
switch playType {
case .typeDefault:
if currentSongIndex == 0 {
currentSongIndex = 6
}
else {
currentSongIndex -= 1
}
playSong()
case .typeLoopOne:
if currentSongIndex == 0 {
currentSongIndex = 6
}
else {
currentSongIndex -= 1
}
playSong()
case .typeRandom:
currentSongIndex = Int.random(in:0...6)
playSong()
}
}

調整音量:

@IBAction func volumeChange(_ sender: UISlider) {
player.volume = sender.value
}

還有一些進階的功能就不一一細說,舉凡隨機播放開關、循環方式切換、還有播放時長等等都可以上我的github看看喔,也歡迎多給我一些指點,非常感謝。

操作影片:

程式碼:

參考網站:

--

--