1

is it possible to retrieve the recorded audio file from the document directory? I have looked through the whole internet, but using AVAsset/WKAudioFileAsset does not seem to be the right path.

Is there just the way to convert the recorded audio file to NSData (binary format), send it to the server and then the server will convert the binary data back into the audio file?

I have found this here: https://iosdevcenters.blogspot.com/2016/04/save-and-get-image-from-document.html

(This example is about retrieving images and they have used UIImage) So, I am curious whether there is an equivalent way for retrieving an audio file? Is there a class for audio to save the file into that class just as UIImage for images?

I hope someone can help me out. Thank you very much.

My code looks as follows:

import WatchKit
import Foundation
import AVFoundation

class InterfaceController: WKInterfaceController, AVAudioRecorderDelegate{
    @IBOutlet weak var btn: WKInterfaceButton!
    var recordingSession : AVAudioSession!
    var audioRecorder : AVAudioRecorder!
    var settings = [String : Any]()

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        recordingSession = AVAudioSession.sharedInstance()

        do{
            try recordingSession.setCategory(AVAudioSession.Category.playAndRecord)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission(){[unowned self] allowed in
            DispatchQueue.main.async {
                if allowed{
                    print("Allow")
                } else{
                    print("Don't Allow")
                }
            }
        }
    }
        catch{
            print("failed to record!")
        }
        // Configure interface objects here.

   // Audio Settings

        settings = [
            AVFormatIDKey:Int(kAudioFormatLinearPCM),
            AVSampleRateKey:44100.0,
            AVNumberOfChannelsKey:1,
            AVLinearPCMBitDepthKey:8,
            AVLinearPCMIsFloatKey:false,
            AVLinearPCMIsBigEndianKey:false,
            AVEncoderAudioQualityKey:AVAudioQuality.max.rawValue

            ]

    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()

        print("Test")
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }


    func directoryURL() -> URL? {
        let fileManager = FileManager.default
        let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = urls[0] as URL
        let soundUrl = documentDirectory.appendingPathComponent("sound.wav")
  //      var soundUrlStr = soundUrl?.path
        //print(fileManager.fileExists(atPath: soundUrlStr))

        let filePath = (soundUrl).path
            print(filePath)

        print("URL")
        print(soundUrl)
        return soundUrl as URL?

    }



    func startRecording(){
        let audioSession = AVAudioSession.sharedInstance()

        do{
            audioRecorder = try AVAudioRecorder(url: self.directoryURL()! as URL,
            settings: settings)
            audioRecorder.delegate = self
            audioRecorder.prepareToRecord()
            audioRecorder.record(forDuration: 5.0)

        }
        catch {
            finishRecording(success: false)
        }

        do {
            try audioSession.setActive(true)
            audioRecorder.record()
        } catch {
        }
    }

    func finishRecording(success: Bool) {
        audioRecorder.stop()
        if success {
            print(success)
        } else {
            audioRecorder = nil
            print("Somthing Wrong.")
        }
    }


    @IBAction func recordAudio() {

        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let url = URL(fileURLWithPath: path)
        let pathPart = url.appendingPathComponent("sound.wav")
        let filePath = pathPart.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath){
            print("File exists!")
            let audioAsset = WKAudioFileAsset(url:pathPart)
           // let playerItem  = WKAudioFilePlayerItem(asset:audioAsset)
            print("Audio File")
            print(audioAsset)
            print("WAV file")
            print(NSData(contentsOfFile: filePath) as Any)
        }else{
            print("File does not exist")
        }


        if audioRecorder == nil {
            print("Pressed")
            self.btn.setTitle("Stop")
            self.btn.setBackgroundColor(UIColor(red: 119.0/255.0, green: 119.0/255.0, blue: 119.0/255.0, alpha: 1.0))
            self.startRecording()


        } else {
            self.btn.setTitle("Record")
            print("Pressed2")
            self.btn.setBackgroundColor(UIColor(red: 221.0/255.0, green: 27.0/255.0, blue: 50.0/255.0, alpha: 1.0))
            self.finishRecording(success: true)

        }
    }

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if !flag {
            finishRecording(success: false)
        }
    }

}


  • 1
    Didn't you get NSData from `NSData(contentsOfFile: filePath)` in `recordAudio()` ? you can use this NSData to send it to server. Recording will be saved to file since it takes output file url. – NeverHopeless May 27 '19 at 04:39
  • @NeverHopeless: is this the only proper way?? Yeah, I attempted to do it. And afterwards the server will convert that binary data to an audio file (e.g .wav file)? Besides NSData there is no other way like the example with UIImage for the case of retrieving the audio? – super_th_91 May 27 '19 at 04:50
  • NSData is the buffer of bytes and in iOS, in order to convert from one form to another you need to convert it to NSData first. e.g., save user object to UserDefaults you have to convert user object to NSData first and then save it to UserDefault and on retrieve you convert NSData back to user object. Same is the case for files as well (.wav/txt to NSData then NSData to .txt/.wav). At least I haven't seen any way to do this without NSData. So from my side yes this is the proper way. – NeverHopeless May 27 '19 at 06:19

0 Answers0