2016-08-24 78 views
3

我目前正在用Swift构建一个iPhone应用程序,我想从我的应用程序发送音频文件到我的网络服务器。我目前使用MPMediaPickerController,这让我我的应用程序中选择音频文件,但一旦我选择文件,它不断告诉我:iOS发送音频文件到网络服务器

的iPod库://item/item.mp3 ID = 12341234

我无法将文件发送到我的Web服务器。我需要以NSData的格式将音频文件发送到我的网络服务器。任何人都可以照亮一盏灯为:

1)什么我可以做错了,或者

2)另一种方式来发送音频文件?

+1

分享自己当前的源代码上传服务器端 – ddb

回答

1
import AssetsLibrary, 
import AVFoundation, 
import MediaPlayer, 
var soundFileURL:URL!, 
var audio_data: Data? = nil** 

    func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) 
    { 
     let item = mediaItemCollection.items[0] as? MPMediaItem ?? MPMediaItem() 
     let url: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL 

     exportiTunesSong(assetURL: url!) 
     { 
      (response) in 
      print(response ?? "responce") 
     } 

     let songTitle: String = item.value(forProperty: MPMediaItemPropertyTitle) as! String 
     lbl_for_file_name.text = songTitle 

     self.dismiss(animated: true, completion: nil) 
    } 


    func mediapicker() 
    { 
     let mediaPicker = MPMediaPickerController(mediaTypes: .music) 
     mediaPicker.delegate = self 
     present(mediaPicker, animated: true, completion: {}) 
    } 


    func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) 
    { 
     print("User selected Cancel tell me what to do") 
     self.dismiss(animated: true, completion: nil) 
     mediaPicker.dismiss(animated: true) { _ in } 

    } 

    func exportiTunesSong(assetURL: URL, completionHandler: @escaping (_ fileURL: URL?) ->()) { 

     let songAsset = AVURLAsset(url: assetURL, options: nil) 

     let exporter = AVAssetExportSession(asset: songAsset, presetName: AVAssetExportPresetAppleM4A) 

     exporter?.outputFileType = "com.apple.m4a-audio" 

     exporter?.metadata = songAsset.commonMetadata 

     let filename = AVMetadataItem.metadataItems(from: songAsset.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon) 


     var songName = "Unknown" 

     if filename.count > 0 { 
      songName = ((filename[0] as AVMetadataItem).value?.copy(with: nil) as? String)! 
     } 

     //Export mediaItem to temp directory 
      exportURL = URL(fileURLWithPath: NSTemporaryDirectory()) 
      .appendingPathComponent(songName) 
      .appendingPathExtension("m4a") 

     exporter?.outputURL = exportURL 
     do 
     { 
      self.audio_data = try Data.init(contentsOf: exportURL!) 
      print("here audio data is \(self.audio_data!)") 

     } catch { 
      print(error) 
     } 
    } 

P.S使用Audio_data发送或使用Alamofire

相关问题