2017-06-04 182 views
0

我正在嘗試爲我的學校項目製作音樂播放器應用程序。無法讓音樂播放到我的音樂播放器應用程序

當我運行的應用程序的一切事情的作品,除了一個事實,當我點擊一首歌不能播放。

請幫我一個詳細的解釋,所以我可以修復應用程序。

下面是代碼:

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

你只是初始化audioPlayer不問它來播放,嘗試在didSelectRow添加此之後,就阻止audioPlayer初始化

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