如何使用swift将音频文件保存在ios中的文件管理器中,如何获取它?

时间:2019-02-12 13:19:16

标签: ios swift

我使用此代码来录制音频。

func record() -> Bool {
    var settings: [String: Any]  = [String: String]()
    settings[AVFormatIDKey] = kAudioFormatLinearPCM
    settings[AVSampleRateKey] = 8000.0
    settings[AVNumberOfChannelsKey] = 1
    settings[AVLinearPCMBitDepthKey] = 16
    settings[AVLinearPCMIsBigEndianKey] = false
    settings[AVLinearPCMIsFloatKey] = false
    // settings[AVAudioQuality] = AVEncoderAudioQualityKey

    let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory,    .allDomainsMask, true)
    let documentPath_ = searchPaths.first
    let pathToSave = "\(String(describing: documentPath_))/\(dateString)"
    let url = URL.init(fileURLWithPath: pathToSave)

    audioRecorder = try? AVAudioRecorder(url: url, settings: settings)

    // Initialize degate, metering, etc.
    audioRecorder.delegate = self;
    audioRecorder.isMeteringEnabled = true;
    audioRecorder?.prepareToRecord()
    if let recordIs = audioRecorder {
        return recordIs.record()
    }
    return false
}

然后我使用此代码从文件管理器获取文件并播放它,但是每次arrayListOfRecordSound为空时。**

func play() {
    let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory,  .allDomainsMask,   true)

    let documentPath_ = searchPaths.first
    let fileManager = FileManager.default
    let arrayListOfRecordSound: [String  ]
    //if fileManager.fileExists(atPath: getDocumentsDirectory()){
    arrayListOfRecordSound = try! fileManager.contentsOfDirectory(atPath: documentPath_!)
    //   }
    print(searchPaths)
    print(documentPath_ as Any)
    print(arrayListOfRecordSound)
    let selectedSound="\(String(describing: documentPath_))/\(String(describing: arrayListOfRecordSound.first))"
    let url = URL.init(fileURLWithPath: selectedSound)
    let player=try? AVAudioPlayer(contentsOf: url)
    player?.delegate = self
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord,
                                                     mode: AVAudioSession.Mode.default,
                                                     options: AVAudioSession.CategoryOptions.defaultToSpeaker)
    player?.prepareToPlay()
    player?.play()
}

0 个答案:

没有答案