从文档目录获取音频文件

时间:2019-05-25 20:00:54

标签: ios swift watchkit

我已经浏览了整个互联网,找到了一种从文档目录中获取整个录制的音频文件的方法。有什么办法吗?您通常通过AVAsset / WKAudioFileAsset吗? 我尝试打印资产,并且在这里得到了类似的信息:

这些是.wav文件吗?

我需要录制的.wav文件才能将它们发送到服务器。

我希望有人能帮助我。非常感谢你。

下面是整个代码:http://s000.tinyupload.com/?file_id=38128676605242153939

这是我的代码:

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

}

0 个答案:

没有答案