从文档目录中检索音频文件

时间:2019-05-27 04:27:12

标签: ios swift audio watchkit

是否可以从文档目录中检索录制的音频文件?我已经浏览了整个互联网,但是使用AVAsset / WKAudioFileAsset似乎并不是正确的方法。

是否存在将录制的音频文件转换为NSData(二进制格式),将其发送到服务器然后服务器将二进制数据转换回音频文件的方法?

我在这里找到了这个:https://iosdevcenters.blogspot.com/2016/04/save-and-get-image-from-document.html

(此示例是有关检索图像的,它们已经使用了UIImage) 因此,我很好奇是否存在检索音频文件的等效方法?是否有一个用于将文件保存到该类中的音频类,就像用于图像的UIImage一样?

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

我的代码如下:

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

}


0 个答案:

没有答案