保存录制的音频(Swift) [英] Saving Recorded Audio (Swift)

查看:189
本文介绍了保存录制的音频(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AVAudioRecorder录制音频,然后将其保存,以便我以后可以使用它。到目前为止,我已经制作了录音机并且它能很好地完成录制并在录制后播放音频,但是一旦我关闭了节目,它就消失了。我能做什么?这是我到目前为止编写的完整代码:

I'm trying to record an audio with AVAudioRecorder and then save it so i can use it later. So far I have Made the Recorder and it does the job well and plays the audio after recording but as soon as i close the program, it's gone. what can I do? Here's the entire code I have written so far :

class RecordViewController: UIViewController , AVAudioPlayerDelegate, AVAudioRecorderDelegate {

@IBOutlet weak var RecordButton: UIButton!
@IBOutlet weak var PlayButton: UIButton!


var soundRecorder : AVAudioRecorder!
var soundPlayer : AVAudioPlayer!
var recordedAudio: RecordedAudio!
var fileName = "audioFile.m4a"



override func viewDidLoad() {
    super.viewDidLoad()

    setupRecorder()


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func setupRecorder() {


    let recordSettings : [String : AnyObject] =
    [
        AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),
        AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue as NSNumber,
        AVEncoderBitRateKey : 320000 as NSNumber,
        AVNumberOfChannelsKey: 2 as NSNumber,
        AVSampleRateKey : 44100.0 as NSNumber
    ]

    do {

      try   soundRecorder = AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
            soundRecorder.delegate = self
            soundRecorder.prepareToRecord()

    } catch {

        print(error)
    }


}

func getCacheDirectory() -> String {

    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 

    return paths[0]

}

func getFileURL() -> NSURL{

    let path  = getCacheDirectory().stringByAppendingPathComponent(fileName)

    let filePath = NSURL(fileURLWithPath: path)

    return filePath
}

func preparePlayer() {

    do {
        try soundPlayer = AVAudioPlayer(contentsOfURL: getFileURL())
        soundPlayer.delegate = self
        soundPlayer.prepareToPlay()
        soundPlayer.volume = 1.0
    } catch {
        print(error)
    }

}

@IBAction func Record(sender: UIButton) {


    if sender.titleLabel?.text! == "Record" {

        soundRecorder.record()
        sender.setTitle("Stop", forState: .Normal)
        PlayButton.enabled = false

    } else {

        soundRecorder.stop()
        sender.setTitle("Record", forState: .Normal)
        PlayButton.enabled = false

    }

}
@IBAction func PlaySound(sender: UIButton) {

    if sender.titleLabel?.text! == "Play" {

        RecordButton.enabled = false
        sender.setTitle("Stop", forState: .Normal)

        preparePlayer()
        soundPlayer.play()

    } else {

        soundPlayer.stop()
        sender.setTitle("Play", forState: .Normal)
    }


}



func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
    PlayButton.enabled = true
    recordedAudio = RecordedAudio()
    recordedAudio.filePathUrl = recorder.url
    recordedAudio.title = recorder.url.lastPathComponent
    print(recordedAudio.title)



}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
    RecordButton.enabled = true
    PlayButton.setTitle("Play", forState: .Normal)
}


推荐答案

我认为该文件可能仍然在那里应用程序退出,问题是您的 viewDidLoad()方法立即调用 setupRecorder(),这反过来创建一个新的 AVAudioRecorder 使用与上次完全相同的文件名 - 覆盖您的工作。

I think the file is probably still there when the app quits, the problem is that your viewDidLoad() method immediately calls setupRecorder(), which in turn creates a new AVAudioRecorder using exactly the same filename as last time – overwriting your work.

帮助您重新安排代码,转到 audioRecorderDidFinishRecording()并将 print(recordedAudio.title)更改为 print(记录器) .URL)。如果您在iOS模拟器中运行,它将为您提供一条到OS X磁盘驱动器上的确切文件名的长路径。

To help you re-arrange your code, go to audioRecorderDidFinishRecording() and change print(recordedAudio.title) to print(recorder.url). If you're running in the iOS Simulator that will give you a long path to an exact filename on your OS X disk drive.

如果您使用Finder浏览那里,那么'将能够看到您的audioFile.m4a文件被反复创建和覆盖,这将让您准确查看问题发生的时间。如果您想查看确切的问题,请在调用 prepareToPlay()时在代码中设置断点,检查文件的大小,然后按F6执行该行代码,然后再次检查文件的大小 - 你应该看到它被清除:)

If you browse there using Finder you'll be able to see your "audioFile.m4a" file being created and overwritten again and again, which will let you see exactly when your problem occurs. If you want to see the exact problem, set a breakpoint in your code when you call prepareToPlay(), check your file's size, then press F6 to execute that line of code, then check your file's size again – you should see it being cleared :)

解决方案可能是每次都生成一个新的文件名。如果您愿意,可以使用 NSUUID

The solution is probably to generate a new filename every time. You could use NSUUID for that if you wanted:

let filename = NSUUID().UUIDString + ".m4a"

您可能会发现我的AVAudioRecorder教程很有用。

注意:您的 getCacheDirectory()方法命名不佳。它正在获取文档目录,而不是缓存目录,这在尝试调试此类问题时有点像红色鲱鱼。

Note: your getCacheDirectory() method is poorly named. It's fetching the documents directory, not the caches directory, which is a bit of a red herring when trying to debug issues like this.

这篇关于保存录制的音频(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆