我正在尝试为我的学校项目制作音乐播放器应用程序。
当我运行应用程序时,一切都有效,除了我点击一首不播放的歌曲这一事实。
请帮我详细说明,以便我修复该应用。
以下是代码:
import UIKit
import AVFoundation
var songs:[String] = []
var audioPlayer = AVAudioPlayer()
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTabelView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = songs[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
do
{
if let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3") {
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath) as URL)
}
} catch {
print(error.localizedDescription)
}
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
gettingSongName()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func gettingSongName() // Get the names of all the songs
{
let folderUrl = URL(fileURLWithPath: Bundle.main.resourcePath!)
do
{
let songPath = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) // Axcess all of the song files
for song in songPath
{
var mySong = song.absoluteString
if mySong.contains(".mp3")
{
let findString = mySong.components(separatedBy: "/")
mySong = (findString[findString.count-1])
mySong = mySong.replacingOccurrences(of: "%20", with: " ")
mySong = mySong.replacingOccurrences(of: ".mp3", with: " ")
songs.append(mySong)
}
}
myTabelView.reloadData()
}
catch
{
}
}
}
答案 0 :(得分:0)
你只是在没有要求它播放的情况下初始化audioPlayer,尝试在audioPlayer init之后的didSelectRow do块中添加它
audioPlayer.prepareToPlay()
audioPlayer.volume = 1.0
audioPlayer.play()
audioPlayer.delegate = self