1

I tried to look for a solution but could not find anything. I want to know whether a WKAudioFileAsset is an audio file? Can it be considered as a .wav file? Is it possible to send a WKAudioFileAsset to a php server? Can you post some sample code how to the send a WKAudioFileAsset/AVAsset to the server?

This is the code I have until now. I need the audio file from the document directory.

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

}


  • It looks like the only thing that `WKAudioFileAsset` stores is "[a] reference to an audio file and provides metadata information about that file." So according to the documentation it is not an audio file, just a metadata pointer to one. https://developer.apple.com/documentation/watchkit/wkaudiofileasset – KSigWyatt May 26 '19 at 00:46
  • As far as uploading the audio, you'll likely have to convert it to an `NSData` object before uploading it. Once you do that any server that can take in the bytes via some API should work fine. The API can be language agnostic at that point. – KSigWyatt May 26 '19 at 00:52
  • @KSigWyatt: Thank you for your answer. Is there just the way to convert the recorded data as a binary format (NSData) and then convert that binary data to the audio format at the server side? I am looking for something equivalent like this example https://iosdevcenters.blogspot.com/2016/04/save-and-get-image-from-document.html – super_th_91 May 27 '19 at 04:16
  • This is for images. But, isnt there something equivalent for audio as well? Getting the image they use the class: UIImage. Is there something like that for Audio? – super_th_91 May 27 '19 at 04:18

0 Answers0