xcode制作有歌单的音乐播放器代码
时间: 2023-11-22 20:05:43 浏览: 36
以下是一个简单的音乐播放器的代码,它包括有歌单的功能。你可以在Xcode中创建一个新的项目,并将此代码复制到ViewController.swift文件中。请注意,此代码仅包含基本的播放和暂停功能,你可以根据需要进行更改和扩展。
```swift
import UIKit
import AVFoundation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var songs = ["Song 1", "Song 2", "Song 3"] // 歌曲名称
var songIndex = 0 // 当前播放的歌曲索引
var player: AVAudioPlayer? // 音乐播放器
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// 播放按钮点击事件
@IBAction func playButtonTapped(_ sender: UIButton) {
if player == nil {
playSong()
sender.setTitle("Pause", for: .normal)
} else if player!.isPlaying {
player?.pause()
sender.setTitle("Play", for: .normal)
} else {
player?.play()
sender.setTitle("Pause", for: .normal)
}
}
// 上一首按钮点击事件
@IBAction func previousButtonTapped(_ sender: UIButton) {
songIndex -= 1
if songIndex < 0 {
songIndex = songs.count - 1
}
playSong()
}
// 下一首按钮点击事件
@IBAction func nextButtonTapped(_ sender: UIButton) {
songIndex += 1
if songIndex >= songs.count {
songIndex = 0
}
playSong()
}
// 播放指定的歌曲
func playSong() {
let songName = songs[songIndex]
let path = Bundle.main.path(forResource: songName, ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
title = songName
} catch {
print("Error playing sound: \(error.localizedDescription)")
}
}
// UITableViewDataSource协议方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
// UITableViewDataSource协议方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath)
cell.textLabel?.text = songs[indexPath.row]
return cell
}
// UITableViewDelegate协议方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
songIndex = indexPath.row
playSong()
}
}
```
此代码中songs数组包含所有歌曲的名称,songIndex变量存储当前播放的歌曲的索引。playSong()方法根据当前songIndex播放指定的歌曲。tableView用于显示歌曲列表,并将选定的歌曲播放。在播放器中,播放、暂停、上一首和下一首按钮处理相应的事件。你需要在Main.storyboard中创建这些按钮并连接到相应的IBAction方法。