这就是我向服务器发送音频的方式:
internal func didFinishRecording(_ recorderViewController: RecorderViewController) {
let audioFileURL = recorderView.recording.url
let audioData = try? Data.init(contentsOf: audioFileURL)
QBRequest.tUploadFile(audioData!, fileName: "recording", contentType: "audio/m4a", isPublic: false, successBlock: {(response: QBResponse!, uploadedBlob: QBCBlob!) in
QBChat.instance.addDelegate(self)
let message: QBChatMessage = QBChatMessage()
let uploadedFileID: UInt = uploadedBlob.id
let attachment: QBChatAttachment = QBChatAttachment()
attachment.type = "audio"
attachment.id = "\(uploadedFileID)"
message.attachments = [attachment]
let params : NSMutableDictionary = NSMutableDictionary()
params["save_to_history"] = true
message.customParameters = params
self.dilog?.send(message, completionBlock: {(error: Error?) -> Void in
self.getMessages()
})
}, statusBlock: {(request: QBRequest?, status: QBRequestStatus?) in
self.uploadProgressView.isHidden = false
self.uploadProgressView.progress = status!.percentOfCompletion
if(self.uploadProgressView.progress == 1.0)
{
self.uploadProgressView.isHidden = true
}
}, errorBlock: {(response: QBResponse!) in
print(response)
})
}
这就是我下载音频并将其写入文档目录的方式:
guard let chatItem = self.chatObj else {
return
}
QBRequest.downloadFile(withID: UInt(chatItem.attachments![0].id!)!, successBlock: {(response : QBResponse, audioData: Data) in
DispatchQueue.main.async {
do {
print(audioData)
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent("\(String(describing: chatItem.id!)).m4a")
try audioData.write(to: fileURL)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
self.player = try AVAudioPlayer.init(contentsOf: fileURL)
print(self.player)
self.player?.prepareToPlay()
self.player?.play()
} catch {
print(error)
}
} catch {
print(error)
}
}
}, statusBlock: {(request: QBRequest?, status: QBRequestStatus?) in
self.uploadProgressView.isHidden = false
self.uploadProgressView.progress = status!.percentOfCompletion
if(self.uploadProgressView.progress == 1.0)
{
self.uploadProgressView.isHidden = true
}
}, errorBlock: {(response :QBResponse) in
print(response.debugDescription)
})
print(audioData)
打印374694 bytes
,这意味着有一个音频文件。
但是当我尝试播放时,我收到了一条错误消息
错误域= NSOSStatusErrorDomain代码= 1685348671"(null)"
我在google上搜索了很多东西,但没有任何效果。
我正在使用THIS lib进行录制。
录制的默认设置为:
let settings: [String: AnyObject] = [
AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless) as Int32),
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
AVEncoderBitRateKey: bitRate as AnyObject,
AVNumberOfChannelsKey: channels as AnyObject,
AVSampleRateKey: sampleRate as AnyObject
]