录制声音看起来不错但播放不起作用

时间:2015-10-08 13:42:41

标签: ios swift swift2 avaudioplayer avaudiorecorder

以下代码应该录制音频然后播放。录制时一切都很好,但它不会播放。有没有人遇到同样的问题或有谁知道我该怎么做才能解决这个问题?

var filename="/audioFile.caf"
    var soundRecorder:AVAudioRecorder!
    var soundPlayer:AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupRecorder()    }



    func setupRecorder() {
        let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
            AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
            AVNumberOfChannelsKey : NSNumber(int: 1),
            AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue)),
            AVEncoderBitRateKey : NSNumber(int: Int32(320000))]
        var error:NSError?
        do {
        soundRecorder=try AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
            soundRecorder.delegate=self
            soundRecorder.prepareToRecord()
        }
        catch {
        }
    }
    func getCacheDictionary() -> String {
        let paths=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) 
        return paths[0]
    }
    func getFileURL() -> NSURL {
        let path=getCacheDictionary().stringByAppendingString(filename)
        let filePath=NSURL(fileURLWithPath: path)
        return filePath
    }
    @IBAction func recordingButton(sender: UIButton) {
        soundRecorder.record()
    }

    @IBAction func Play(sender: AnyObject) {
        do {
        soundPlayer=try AVAudioPlayer(contentsOfURL: getFileURL())
            soundPlayer.delegate=self
            soundPlayer.prepareToPlay()
            soundPlayer.play()
        }
        catch {


        }
    }
    @IBAction func PauseRecording(sender: AnyObject) {
        soundRecorder.pause()
    }

1 个答案:

答案 0 :(得分:0)

你必须在播放前停止录音机(关闭声音文件)。

<{1>}中的

,请点击顶部:

@IBAction func Play(sender: AnyObject)

这来自documentation的<{1}}方法的摘要:

  

停止录制并关闭音频文件。