通过AVAudioRecorder将录制保存到Core数据

时间:2017-09-02 19:20:57

标签: ios swift core-data avaudioplayer avaudiorecorder

我正在尝试构建一个简单的录音应用程序,它从麦克风输入并在按下停止时保存录音,然后播放器从本地存储中检索录音并播放。

以下代码允许用户录制音频并将其保存到URL并从同一URL播放。

我想要做的是当我按下停止时将音频保存到Coredata,并在按下播放时从Coredata中检索音频。

@IBOutlet weak var RecordBTN: UIButton!
@IBOutlet weak var AddBTN: UIButton!

// Variables handeling Recording and Playing
var SoundRecorder : AVAudioRecorder!
var SoundPlayer : AVAudioPlayer!

 override func viewDidLoad() {
    super.viewDidLoad()
    // Keeps constraints when we run the app
    self.view.layoutIfNeeded()
    setupRecorder() 
}

func setupRecorder()
{
    // Format: Lossless audio
    // Quality: Max of raw value
    // Bit Rate: 320 Kb/s [ AppleMusic: 256 Kb/s, Spotify: 320 Kb/s]
    let recordSettings : [String : AnyObject] =
        [AVFormatIDKey : NSNumber(value: kAudioFormatAppleLossless as UInt32),
         AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue as NSNumber,
         AVEncoderBitRateKey : 320000 as NSNumber,
         AVNumberOfChannelsKey : 2 as NSNumber,
         AVSampleRateKey : 44100.0 as NSNumber]

    do {

        // Initiallizing SoundRecorder
        // as [NSObject : AnyObject] after recordSettings
        try SoundRecorder = AVAudioRecorder(url: getFileURL(),
                                            settings: recordSettings as [String : AnyObject])

    } catch {
        // Catches any error
        print("Something's went wrong with setting up the audio")
    }

    // Preparing sound recorder to record
    SoundRecorder.delegate = self
    SoundRecorder.prepareToRecord()


}


func getCacheDir() -> String
{
    // Where audio files will be held
    // Search inside documents inside of the app
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
                                                    FileManager.SearchPathDomainMask.userDomainMask, true) as [String]
    return paths[0]
}

func getFileURL() -> URL
{
    // Finding the file path to the specified file name
    let path = (getCacheDir() as NSString).appendingPathComponent(fileName)
    let filePath = URL(fileURLWithPath: path)

    return filePath
}


func preparePlayer()
{
    do{
        try SoundPlayer = AVAudioPlayer(contentsOf: getFileURL())
    } catch {
        print("Somethingwrong with the Sound Player")
    }
    SoundPlayer.delegate = self
    SoundPlayer.prepareToPlay()
    SoundPlayer.volume = 10.0
}



@IBAction func Record(_ sender: UIButton) {
    if (sender.titleLabel?.text == "Record")
    {
        SoundRecorder.record();
        sender.setTitle("Stop", for: UIControlState())
        sender.setImage(UIImage (named: "StopBTN"), for: UIControlState())
        PlayBTN.isEnabled = false
        progressBar.progress = Float(SoundRecorder.currentTime)

    }
    else
    {
        SoundRecorder.stop();
        sender.setTitle("Record", for: UIControlState())
        sender.setImage(UIImage (named: "RecordBTN"), for: UIControlState())
        PlayBTN.isEnabled = true
    }

}


    @IBAction func Play(_ sender: UIButton) {
    if(sender.titleLabel?.text == "Play")
    {
        RecordBTN.isEnabled = false
        sender.setTitle("Stop", for: UIControlState())
        sender.setImage(UIImage (named: "StopBTN"), for: UIControlState())
        preparePlayer()
        SoundPlayer.play()
    }
    else if (sender.titleLabel?.text == "Stop" || (SoundPlayer.currentTime == SoundPlayer.duration))
    {
        SoundPlayer.stop()
        sender.setTitle("Play", for: UIControlState())
        sender.setImage(UIImage (named: "PlayBTN"), for: UIControlState())
        RecordBTN.isEnabled = true
    }
}

我在Coredata中添加了Recordings实体,仍然对使用什么属性感到困惑,不知道我是否会保存URL或二进制文件。

0 个答案:

没有答案