【问题标题】:AVAudioRecorder.record() always returns "false" in iOS 8AVAudioRecorder.record() 在 iOS 8 中总是返回“false”
【发布时间】:2014-12-05 13:41:39
【问题描述】:

我正在尝试使用 AVAudioRecorder 创建一个练习应用程序,按下按钮后,它会通过 iPhone 的麦克风将 1 秒的音频录制到一个名为“Test.wav”的文件中并播放。但是,每次我尝试执行它们时,record() 和 recordForDuration() 方法似乎都失败了。我已经尝试设置 AVAudioSession 并使其处于活动状态,但似乎没有任何效果。任何帮助将不胜感激。

import UIKit

导入 AVFoundation

类 ViewController: UIViewController, AVAudioRecorderDelegate {

@IBOutlet var recordAndPlayButton: UIButton!

let settings = [
    AVFormatIDKey: kAudioFormatLinearPCM,
    AVSampleRateKey: 192000.0,
    AVNumberOfChannelsKey: 1,
    AVLinearPCMBitDepthKey: 16,
    AVLinearPCMIsBigEndianKey: false,
    AVLinearPCMIsFloatKey: false,
    AVLinearPCMIsNonInterleaved: false
]

var audioSession = AVAudioSession.sharedInstance()
var recorder : AVAudioRecorder!

override func viewDidLoad() {
    audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
    audioSession.setActive(true, error: nil)

    recorder = AVAudioRecorder(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Test", ofType: "wav")!), settings: settings, error: nil)
    recorder.delegate = self
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func recordSoundAndPlay() {
    recorder.prepareToRecord()
    println(recorder.recordForDuration(1.0))

    var testSound = SystemSoundID()
    AudioServicesCreateSystemSoundID(NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Test", ofType: "wav")!), &testSound)
    AudioServicesPlaySystemSound(testSound)
}

}

【问题讨论】:

    标签: ios iphone xcode swift


    【解决方案1】:

    我也遇到过这个问题 - 事实证明这实际上与 AVAudioRecorder 无关,而实际上与 iOS8 中用户目录的结构方式有关。有关更多信息,请参阅this 问答。

    无论如何,我通过将文件的访问方式更改为类似这样的方式来修复它:

    let DOCUMENTS_FOLDER: NSString! = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as NSString
    
    @IBAction func recordSoundAndPlay() {
        recorder.prepareToRecord()
        println(recorder.recordForDuration(1.0))
    
        var testSound = SystemSoundID()
        AudioServicesCreateSystemSoundID(NSURL(fileURLWithPath: "\(DOCUMENTS_FOLDER)/Test.wav")), &testSound)
        AudioServicesPlaySystemSound(testSound)
    }
    

    告诉我进展如何!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多