【发布时间】:2016-12-09 12:53:53
【问题描述】:
我正在访问 iTunes 库音乐。我将一首选定的歌曲存储在我的 Documents 目录中。歌曲大小为 13MB,我需要减小歌曲大小以便可以轻松将其发送到服务器。我该怎么做?这是我的整体代码:
func mediaPicker(mediaPicker: MPMediaPickerController,
didPickMediaItems mediaItemCollection: MPMediaItemCollection){
let item: MPMediaItem = mediaItemCollection.items[0]
print(mediaItemCollection)
print("mediaItemCollection = \(mediaItemCollection)")
let url = item.valueForProperty(MPMediaItemPropertyAssetURL) as! NSURL
FinalAudioName = item.valueForProperty(MPMediaItemPropertyTitle) as! NSString as String
export(url, completionHandler: { _, _ in })
}
func export(assetURL: NSURL, completionHandler: (NSURL?, ErrorType?) -> ())
{
let asset = AVURLAsset(URL: assetURL)
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
completionHandler(nil, ExportError.unableToCreateExporter)
return
}
fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
.URLByAppendingPathComponent(NSUUID().UUIDString)!
.URLByAppendingPathExtension("m4a")!
print(fileURL)
let recordSettings:[String : AnyObject] = [
AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),
AVEncoderBitRateKey : 16000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100,
AVEncoderAudioQualityKey: AVAudioQuality.Medium.rawValue
]
do
{
audioRecorder = try AVAudioRecorder(URL: fileURL, settings: recordSettings)
audioRecorder!.delegate = self
audioRecorder!.meteringEnabled = true
audioRecorder!.prepareToRecord()
}
catch let error as NSError
{
audioRecorder = nil
print(error.localizedDescription)
}
do {
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
}
catch _
{
}
exporter.outputURL = fileURL
exporter.outputFileType = AVFileTypeAppleM4A
exporter.exportAsynchronouslyWithCompletionHandler {
if exporter.status == .Completed {
completionHandler(self.fileURL, nil)
self.optData = NSData(contentsOfURL: self.fileURL)!
print(self.optData)
} else
{
completionHandler(nil, exporter.error)
}
}
mediaPicker!.dismissViewControllerAnimated(true, completion: nil)
}
【问题讨论】:
-
您需要在这里提供更多帮助,以便我们为您提供帮助。你的代码是否工作,如果没有......它有什么问题,它会抛出任何错误,输出文件大小是否相同?
-
代码工作正常..self.optData = NSData(contentsOfURL: self.fileURL)! print(self.optData)..数据很大我想减少
-
比特率通常是对音频文件的文件大小产生较大差异的属性(虽然我不是专家)。我引用了我在 wikipedia 上找到的内容“你在 iTunes 上购买的音乐是每秒 256 千比特,这意味着一首歌曲的每一秒中存储了 256 千比特的数据”。将比特率降低到 16 KB 应该会有很大的不同。新的文件大小是多少。你能提供一个我可以玩的样本吗?
-
其实我不想把所有歌曲都保存在我的目录中。主要是我必须将选定的 iTunes 歌曲上传到 php 服务器。我们不能直接上传原始 mp3 对吗?这就是为什么我将所选歌曲存储在本地并上传。一旦我添加另一首歌曲,如果上传成功,我将清除该歌曲一次。好的..我会尽力让你知道
标签: ios swift xcode itunes mpmediapickercontroller