简体   繁体   中英

How to save audio recorded file by user input using Swift?

My scenario, I am trying to create audio record and save file into iPhone documentdirectory .

I have done recording functionality but I need to implement save file name based on user input. After audio record , If user click save button I am asking file name to user by alertviewcontroller with textfield .

Here, my audio file saving by static file name(audio.m4a) because inside viewdidload I implemented save document directory code but I dont know how to implement save file name based on user input within save action.

override func viewDidLoad() {
  super.viewDidLoad() 
  let session = AVAudioSession.sharedInstance()
        try? session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try? session.overrideOutputAudioPort(.speaker)
        try? session.setActive(true)
        if let basePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            let baseComponents = [basePath,"audio.m4a"]
            if let audioURL = NSURL.fileURL(withPathComponents: baseComponents) {
                var settings: [String: Any] = [:]
                self.audioURL = audioURL
                settings[AVFormatIDKey] = Int(kAudioFormatMPEG4AAC)
                settings[AVSampleRateKey] = 44100.0
                settings[AVNumberOfChannelsKey] = 2
                audioRecorder = try? AVAudioRecorder(url: audioURL, settings: settings)
                audioRecorder?.prepareToRecord()
            }
        }
}

@IBAction func record_click(_ sender: Any) {
        if let audioRecorder = self.audioRecorder {
            if (audioRecorder.isRecording) {
                audioRecorder.stop()
           } else {
                audioRecorder.record()
            }
        }
    }

// Within below action I am calling alertview with textfield for asking file name
@IBAction func save_click(_ sender: Any) {
   self.savefileAlertView()
}

If you want to set name of file which has been already saved you can rename it.

You can create this function

func renameAudio(newTitle: String) {
    do {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let documentDirectory = URL(fileURLWithPath: path)
        let originPath = documentDirectory.appendingPathComponent("audio.m4a")
        let destinationPath = documentDirectory.appendingPathComponent("\(newTitle).m4a")
        try FileManager.default.moveItem(at: originPath, to: destinationPath)
    } catch {
        print(error)
    }
}

And in your alert controller use it and as parameter pass text of text field inside alert.

import UIKit
import AVFoundation
import Speech

class ViewController: UIViewController,AVSpeechSynthesizerDelegate {

var utterance = AVSpeechUtterance()
let synthesizer = AVSpeechSynthesizer()

var filename : String       = "audio.m4a"

@IBOutlet weak var speechBtnOutlet: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()



    utterance = AVSpeechUtterance(string: self.textView.text)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
    utterance.rate = 0.1
    synthesizer.delegate = self
    synthesizer.speak(utterance)

}

func renameAudio(newTitle: String) {
    do {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let documentDirectory = URL(fileURLWithPath: path)

        let originPath = documentDirectory.appendingPathComponent(utterance.speechString)

        let destinationPath = documentDirectory.appendingPathComponent("\(newTitle).m4a")
        try FileManager.default.moveItem(at: originPath, to: destinationPath)

    } catch {
        print(error)
    }
}



  @IBAction func speechBtn(_ sender: Any) {       
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM