swift - 在 tableview 中显示文档目录中的音频文件并在 swift 3 中选择行时播放音频文件

标签 swift audio avfoundation avaudioplayer

我正在将录音文件保存在 iPhone 文档目录中,并在 tableview 中显示保存文件,但在选择保存的音频文件时无法播放。

最佳答案

我使用了 Collection View ,你可以简单地用 tableView 替换 Collection View 的选择方法

import UIKit
import AVFoundation

let reuseIdentifier = "recordingCell"

class RecordingsCollectionViewController: UICollectionViewController {

    var recordings = [URL]()
    var player:AVAudioPlayer!


    override func viewDidLoad() {
        super.viewDidLoad()
        listRecordings()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.recordings.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RecordingCollectionViewCell

        cell.label.text = recordings[(indexPath as NSIndexPath).row].lastPathComponent

        return cell
    }

    // MARK: UICollectionViewDelegate

    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }


    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("selected \(recordings[(indexPath as NSIndexPath).row].lastPathComponent)")
        play(recordings[(indexPath as NSIndexPath).row])

    }

    func play(_ url:URL) {
        print("playing \(url)")

        do {
            self.player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.volume = 1.0
            player.play()
        } catch let error as NSError {
            self.player = nil
            print(error.localizedDescription)
        } catch {
            print("AVAudioPlayer init failed")
        }

    }
    func listRecordings() {

        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let urls = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
            self.recordings = urls.filter( { (name: URL) -> Bool in
                return name.lastPathComponent.hasSuffix("m4a")
            })

        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("something went wrong listing recordings")
        }

    }
}

extension RecordingsCollectionViewController: FileManagerDelegate {

    func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool {

        print("should move \(srcURL) to \(dstURL)")
        return true
    }

}

关于swift - 在 tableview 中显示文档目录中的音频文件并在 swift 3 中选择行时播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44898572/

相关文章:

ios - 将数据从结构数组传递到新的 TableView Controller

c# - 每秒播放不同的WAV声音吗?是从磁盘还是从内存?

c++ - 访问 Windows 声音?

ios - 从 iOS 中捕获的视频中获取慢动作元数据

swift - 闭包返回值(以前的 completionBlock)

ios - 保持导航 Controller 的状态,只改变 View

带有前台服务的音频播放器,适用于 iOS+ Android

ios - AVCaptureVideoData输出分辨率

swift - 如何创建 CMVideoFormatDescription 对象

ios - Swift Avplayer - 当点击 'Play' 时,停止所有其他 tableviewcells 播放