如何使用swift播放系统声音?

时间:2020-06-24 17:10:21

标签: ios swift

我已经编写了这段代码,以便在表格视图中显示所有系统声音。问题是我一直都没有声音:|如果你们能告诉我我做错了什么,那可能会很酷:

   class CompletetedSoundViewController: UITableViewController {
    
    private var soundList: [String] = []
    private let soundDirectory = "/System/Library/Audio/UISounds"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "trackCell")
        soundList = FileManager.default.enumerator(atPath: soundDirectory)!.map { String(describing: $0) }
    }

    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return soundList.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "trackCell", for: indexPath)
        let soundFileName = soundList[indexPath.row]
        let fullyQualifiedName = soundDirectory + "/" + soundFileName
        let url = URL(fileURLWithPath: fullyQualifiedName)

        var soundId: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
        cell.textLabel?.text = "\(soundFileName) \(soundId)"
       
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let soundFileName = soundList[indexPath.row]
        let fullyQualifiedName = soundDirectory + "/" + soundFileName
        let url = URL(fileURLWithPath: fullyQualifiedName)
        var soundId: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
        AudioServicesPlaySystemSound(soundId)
    }
    
}
   

0 个答案:

没有答案