在swift中录制音频并将录制的音频传递给下一个视图控制器

时间:2015-05-10 03:36:06

标签: ios swift audio

我正在尝试录制音频,并将录制的音频传递给下一个视图控制器。这是我录制音频的代码

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {

@IBOutlet weak var recording: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var stopButton: UIButton!

var audioRecorder:AVAudioRecorder!

var recordedAudio : RecordedAudio!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

override func viewWillAppear(animated: Bool) {
   // enables record button 
    // hides the stop button
    recordButton.enabled = true
    stopButton.hidden = true

}
@IBAction func recordAudio(sender: UIButton) {
    //Shows recording label
    recording.hidden = false

    //diabling record button
    recordButton.enabled = false
    stopButton.hidden = false

    //Filepath Creation
    let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String

    let currentDateTime = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "ddMMyyyy-HHmmss"
    let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
    let pathArray = [dirPath, recordingName]
    let filePath = NSURL.fileURLWithPathComponents(pathArray)
    println(filePath)

    // Recording Session

    var session = AVAudioSession.sharedInstance()
    session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)

    audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)

    audioRecorder.delegate = self
    audioRecorder.meteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()

}



func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
    // ToDo create recorded audio file
    if(flag)
    {   recordedAudio = RecordedAudio()

        recordedAudio.filepathURL = recorder.url

        recordedAudio.title = recorder.url.lastPathComponent

    // ToDo Perform segue

        self.performSegueWithIdentifier("stopRecording", sender: recordedAudio)
    }
    else {
        println("Recording was unsuccessfull")
        stopButton.hidden = true
        recordButton.enabled = true

    }
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue == "stopRecording") {

        let PlaySoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController
        let data = sender as! RecordedAudio

        PlaySoundsVC.receivedAudio = data
    }
}


@IBAction func stopAudio(sender: UIButton) {
    // Hides recording
    recording.hidden = true
    audioRecorder.stop()
    var audioSession = AVAudioSession.sharedInstance()
    audioSession.setActive(false, error: nil)

}
}

我的模型类是,

import Foundation

class RecordedAudio : NSObject{

    var filepathURL :NSURL!
    var title : String!
}

以下是我的第二个viewcontroller如何捕获数据并使用它,

    class PlaySoundsViewController: UIViewController {

    var audioPlayer: AVAudioPlayer!
    var receivedAudio: RecordedAudio!

    func rateplay (rtt : Float32) {
        audioPlayer.stop()

        audioPlayer.rate = rtt

        audioPlayer.currentTime = 0.0
        audioPlayer.play()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
//        if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")
//        {
//        // if path is there for mp3
//          let filepathurl = NSURL.fileURLWithPath(filePath)
//            
//          // println(receivedAudio.title)
//            
//        }
//        else {
//        println("Path is empty")
//        
//        }
        audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filepathURL, error: nil)
        audioPlayer.enableRate = true




    }

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



    @IBAction func playSlow(sender: UIButton) {
    // play sloooowllyyyyy
        audioPlayer.stop()

        audioPlayer.rate = 0.5

        audioPlayer.currentTime = 0.0

        audioPlayer.play()

    }
    @IBAction func playFast(sender: UIButton) {
       rateplay(1.5)

    }

    @IBAction func stopAudio(sender: UIButton) {
        audioPlayer.stop()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

直到我添加以下代码

audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filepathURL, error: nil)
        audioPlayer.enableRate = true

我能够移动到第二个场景,这意味着音频被成功录制。但是一旦我访问了像#34; receivedAudio.filepathURL"我收到了错误,

fatal error: unexpectedly found nil while unwrapping an Optional value

1 个答案:

答案 0 :(得分:0)

RecordSoundsViewController的prepareForSegue函数中,您需要编写segue.identifier == "stopRecording"作为条件。

目前您有segue == "stopRecording"

快乐的编码!