我正在使用设备麦克风录制音频AVAudioRecorder
返回文件在.caf该格式只能在 Apple 设备上播放,而不能在 Android 设备上播放。由于苹果不支持.mp3文件,所以我想将其转换为.mp4上传到服务器之前格式化。
是.mp4仅适用于音频吗?我可以将其转换为AVAssetExportSession
?
以下是录音机代码:
func setupAudioRecorder ()
{
let fileMgr = FileManager.default
let dirPaths = fileMgr.urls(for:.documentDirectory,
in:.userDomainMask)
let soundFileURL = dirPaths[0].appendingPathComponent("myaudio.caf")
let recordSettings =
[AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0] as [String : Any]
do {
try audioSession.setCategory(
AVAudioSessionCategoryPlayAndRecord)
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
}
do {
try audioRecorder = AVAudioRecorder(url: soundFileURL,
settings: recordSettings as [String : AnyObject])
audioRecorder?.prepareToRecord()
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
}
}
经过大量搜索后我能够转换.caf into .mp4使用这段代码
let audioURL = ".caf audio file url"
let fileMgr = FileManager.default
let dirPaths = fileMgr.urls(for: .documentDirectory,
in: .userDomainMask)
let outputUrl = dirPaths[0].appendingPathComponent("audiosound.mp4")
let asset = AVAsset.init(url: audioURL)
let exportSession = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetHighestQuality)
// remove file if already exits
let fileManager = FileManager.default
do{
try? fileManager.removeItem(at: outputUrl)
}catch{
print("can't")
}
exportSession?.outputFileType = AVFileTypeMPEG4
exportSession?.outputURL = outputUrl
exportSession?.metadata = asset.metadata
exportSession?.exportAsynchronously(completionHandler: {
if (exportSession?.status == .completed)
{
print("AV export succeeded.")
// outputUrl to post Audio on server
}
else if (exportSession?.status == .cancelled)
{
print("AV export cancelled.")
}
else
{
print ("Error is \(String(describing: exportSession?.error))")
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)