2017-08-31 138 views
0

我正在使用設備麥克風錄製音頻,其中AVAudioRecorder返回的文件格式爲.caf只能在Apple設備中播放,但不能在Android設備上播放。由於Apple不支持.mp3文件,所以我想在將文件上傳到服務器之前將其轉換爲.mp4格式。 是.mp4僅適用於音頻嗎?我可以使用AVAssetExportSession進行轉換嗎?如何將.caf音頻文件轉換爲swmp中的.mp4文件

以下是錄音機代碼:

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)") 
    } 
} 

回答

0

很多搜​​索的,我能夠利用這段代碼轉換的.caf.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))") 

     } 
    }) 
0

可以在MPEG4 AAC記錄的情況下直接轉換添加工序。使用AVFormatIDKeykAudioFormatMPEG4AAC價值,降低採樣率,以8000或16000

+0

感謝您的後幫助,但我也需要.caf,因爲在上傳到服務器之前,我需要用AVAudioPlayer播放音頻。 –

+0

您可以使用AVAudioPlayer播放AAC。 –

+0

好的,讓我試試這個設置 –