Ios 无法在我的音乐播放器应用程序上播放音乐

Ios 无法在我的音乐播放器应用程序上播放音乐,ios,swift,swift3,avfoundation,Ios,Swift,Swift3,Avfoundation,我正在尝试为我的学校项目制作一个音乐播放器应用程序 当我运行应用程序时,一切都正常,除了当我点击一首歌时,它不会播放 请帮我做一个详细的解释,这样我就可以修复这个应用了 代码如下: import UIKit import AVFoundation var songs:[String] = [] var audioPlayer = AVAudioPlayer() class FirstViewController: UIViewController, UITableViewDelegate,

我正在尝试为我的学校项目制作一个音乐播放器应用程序

当我运行应用程序时,一切都正常,除了当我点击一首歌时,它不会播放

请帮我做一个详细的解释,这样我就可以修复这个应用了

代码如下:

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
        {

        }

    }


}

您只是在初始化audioPlayer而不要求它播放,请尝试在audioPlayer初始化之后的didSelectRow do块中添加此选项

audioPlayer.prepareToPlay()
audioPlayer.volume = 1.0
audioPlayer.play()
audioPlayer.delegate = self