嗨,我必须排除项目中的一些mp3文件,我尝试了 mySong = mySong.replacingOccurrences(of: "Mr. Blue Sky", with: "")
但是在我的表视图中,总是有一个空白的可单击空间播放.mp3。在下面,您可以找到完整的代码。该代码基于通过小组和URL获取信息。仅在此Swift中排除此文件。请帮助我。
import UIKit
import AVFoundation
class viewHappy: UIViewController, UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var myTableView2: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = songs[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
do
{
let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
audioPlayer.play()
thisSong = indexPath.row
audioStuffed = true
}
catch
{
print ("ERROR")
}
}
override func viewDidLoad()
{
super.viewDidLoad()
gettingSongNames()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
//FUNCTION THAT GETS THE NAME OF THE SONGS
func gettingSongNames()
{
let folderURL = URL(fileURLWithPath:Bundle.main.resourcePath!)
do
{
let happyPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
//loop through the found urls
for happySong in happyPath
{
var mySong = happySong.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)
print (findString)
}
}
myTableView2.reloadData()
}
catch
{
print ("ERROR")
}
var session = AVAudioSession.sharedInstance()
do
{
try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}
}
}
如果您有歌曲列表,请说…
struct Song {
let title: String
let mp3: MP3
}
let songs = [Song(title: "Mr. Blue Sky", mp3: mp3_1),
Song(title: "Evil Woman", mp3: mp3_2),
Song(title: "10538 Overture", mp3: mp3_3)]
然后,您可以使用filter
…
let filteredSongs = songs.filter { $0.title != "Mr. Blue Sky" }
然后在您的表视图委托中,返回filteredSongs.count
作为您的numberOfRows