制作一个完整的音乐播放器,包含两个界面:音乐列表界面和播放界面的完整代码
时间: 2024-02-18 19:02:59 浏览: 186
由于完整的音乐播放器代码比较长,无法在这里完整展示。我可以提供一个简单的示例代码,供你参考:
音乐列表界面代码:
```swift
import UIKit
class MusicListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var musicList: [String] = ["Music 1", "Music 2", "Music 3", "Music 4"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MusicCell", for: indexPath)
cell.textLabel?.text = musicList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let musicName = musicList[indexPath.row]
performSegue(withIdentifier: "ShowMusicPlayer", sender: musicName)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowMusicPlayer" {
let musicName = sender as! String
let destinationVC = segue.destination as! MusicPlayerViewController
destinationVC.musicName = musicName
}
}
}
```
播放界面代码:
```swift
import UIKit
import AVFoundation
class MusicPlayerViewController: UIViewController {
@IBOutlet weak var musicNameLabel: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var progressSlider: UISlider!
var musicName: String?
var player: AVAudioPlayer?
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
if let musicName = musicName {
musicNameLabel.text = musicName
}
progressSlider.value = 0
do {
if let musicName = musicName {
let url = Bundle.main.url(forResource: musicName, withExtension: "mp3")!
player = try AVAudioPlayer(contentsOf: url)
player?.prepareToPlay()
}
} catch let error {
print(error.localizedDescription)
}
}
// MARK: - Button actions
@IBAction func playButtonTapped(_ sender: UIButton) {
player?.play()
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] (timer) in
guard let self = self else { return }
self.progressSlider.value = Float(self.player!.currentTime / self.player!.duration)
})
}
@IBAction func pauseButtonTapped(_ sender: UIButton) {
player?.pause()
timer?.invalidate()
timer = nil
}
@IBAction func stopButtonTapped(_ sender: UIButton) {
player?.stop()
player?.currentTime = 0
timer?.invalidate()
timer = nil
progressSlider.value = 0
}
@IBAction func progressSliderChanged(_ sender: UISlider) {
player?.currentTime = TimeInterval(sender.value) * player!.duration
}
}
```
这是一个简单的示例代码,可以展示音乐列表和播放界面的基本功能。你可以根据自己的需求进行修改和完善。
阅读全文