我正在使用AVAudioRecorder在视频中录制音频。当我按“开始”按钮开始录制时,会有很长的延迟,有时会长达6秒才开始录音。然后,录制不成功,并以0.0秒的时间出现在文件中。
**** 帖子已被编辑,以尝试使问题更清晰
我创建了一个示例音频录制项目,我要做的就是尝试录制音频,但对我来说仍然无效。我的代码如下:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioRecorderDelegate {
var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!
var settings = [String : Int]()
var outputAudioLocation: URL!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//setUpAudioSession()
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission { (hasPermission) in
if hasPermission {
print("Accepted")
} else {
print("Not allowed")
}
}
print("audio set up")
} catch {
print("Recording session error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startButtonPressed(_ sender: Any) {
recordAudio()
}
@IBAction func stopButtonPressed(_ sender: Any) {
stopRecordingAudio()
}
func recordAudio() {
// Check if we have an active recorder
if audioRecorder == nil {
outputAudioLocation = getDirectory().appendingPathComponent("audio.m4a")
settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
// Start Audio Recording
do {
audioRecorder = try AVAudioRecorder(url: outputAudioLocation, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
print("audio recording")
} catch {
print("Audio recording hasn't worked")
}
}
}
func stopRecordingAudio() {
if audioRecorder != nil {
audioRecorder.stop()
print("audio stopped recording")
audioRecorder = nil
}
}
//directory for audio recording
func getDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
print("audio recording successful")
} else {
print("audio recording not successful")
}
}
}
****更新
我已经下载了一个使用AVAudioRecorder的GitHub项目,当我在iPhone 6的手机上尝试该录音时,该录音无法正常工作,并且保存时间为0.0。但是,当我使用模拟器(iPhone 8)时,它可以按预期工作。有谁知道为什么这会在我的手机上发生?通过我自己的项目,到今天为止一切正常。
答案 0 :(得分:2)
在浪费了我超过5个小时的时间试图找出我的代码出了什么问题之后,事实证明这是我的iPhone出现的问题。
我关闭并重新打开了手机,录音现在可以正常工作了。我从未想过那会是问题。
感谢@matt试图帮助我!