Search code examples
swiftaudioavfoundationavaudioplayer

Show audio files from document directory in tableview and play audio files on selecting row in swift 3


I am saving audio recordings files in iPhone document directory and shows save files in tableview, but on selecting saved audio files could not play.


Solution

  • i used collection view for that you can simply replace did select method of collection view with tableView

    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
        }
    
    }