我已经使用麦克风录制了.AAC格式的音频并成功保存在文档目录中。当我尝试播放特定录制的音频时,它没有播放但播放方法正在呼叫,麦克风中没有任何声音。如果有人可以帮我解决这个问题
录制音频示例代码
func record() {
self.prepareToRecord()
if let recorder = self.audioRecorder {
recorder.record()
}
}
func prepareToRecord() {
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
str_Recordedname = formatter.stringFromDate(currentDateTime)+".AAC"
let pathArray = [dirPath, str_Recordedname]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 2 as NSNumber,
AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
self.audioRecorder = try AVAudioRecorder(URL:filePath!, settings:[:])
self.audioRecorder!.meteringEnabled = true
self.audioRecorder!.prepareToRecord()
self.audioRecorder!.record()
self.audioRecorder!.delegate = self
print("Recorded Audio is",filePath!)
}
catch let error as NSError
{
print(error.description)
}
}
播放示例代码
var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
print("\nfilePath: \(filePath)")
filePath = filePath.stringByAppendingPathComponent(self.str_Recordedname)
print("\nfilePath: \(filePath)")
let filePathURL = NSURL.fileURLWithPath(filePath as String)
print("\nfilePathURL: \(filePathURL)")
do {
var player = AVPlayer()
let asset = AVURLAsset(URL: filePathURL)
let playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)
player.play()
} catch let error as NSError {
print("Error: ", error.localizedDescription)
}
先谢谢
编辑:
从本地删除AVPlayer变量并在全球范围内粘贴其工作