前提・実現したいこと
テーブルをタッチすると音楽が再生されるようにしたいです
発生している問題・エラーメッセージ
なし
該当のソースコード
swift
1 2import UIKit 3import AVFoundation 4 5var songs:[String] = [] 6var audioPlayer = AVAudioPlayer() 7 8 9class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 10 11 @IBOutlet weak var musicTableView: UITableView! 12 13 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 14 return songs.count 15 } 16 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 17 let musicCell = UITableViewCell(style: .default, reuseIdentifier: "MusicListCell") 18 musicCell.textLabel?.text = songs[indexPath.row] 19 return musicCell 20 } 21 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 22 do { 23 print("aaaaaaaaaaa") 24 let audioPath = Bundle.main.path(forResource: "music/(songs[indexPath.row])", ofType: "mp3") 25 print(audioPath) 26 try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL ) 27 28 } catch { 29 print("error") 30 } 31 } 32 33 override func viewDidLoad() { 34 super.viewDidLoad() 35 // Do any additional setup after loading the view, typically from a nib. 36 37 let songURL1 = URL(fileURLWithPath: Bundle.main.path(forResource: "music/Abolisher", ofType: "mp3")!) 38 let songURL2 = URL(fileURLWithPath: Bundle.main.path(forResource: "music/EndlessDemise", ofType: "mp3")!) 39 let songURL3 = URL(fileURLWithPath: Bundle.main.path(forResource: "music/SantisimaMuerte", ofType: "mp3")!) 40 let songURL4 = URL(fileURLWithPath: Bundle.main.path(forResource: "music/SixFeetUnder", ofType: "mp3")!) 41 let songURL5 = URL(fileURLWithPath: Bundle.main.path(forResource: "music/Unanswered", ofType: "mp3")!) 42 43 let songsURL = [ songURL1, songURL2, songURL3, songURL4, songURL5 ] 44 //print("あああああああああああああ") 45 for song in songsURL { 46 var mysong = song.absoluteString 47 let findString = mysong.components(separatedBy: "/") 48 mysong = findString[findString.count-1] 49 mysong = mysong.replacingOccurrences(of: ".mp3", with: "") 50 songs.append(mysong) 51 } 52 musicTableView.reloadData() 53 } 54} 55
試したこと
タップした曲名のpathを表示させて見たら正しく表示されました。
補足情報(FW/ツールのバージョンなど)
swift4.2
xcode10.0
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/10/27 13:15