Как скачать mp3 файл из MPMediaPickerController, используя язык swift? - PullRequest
0 голосов
/ 24 января 2019

Мое приложение - скачать песню из MPMediaPickerController и сохранить mp3-файл в каталоге документов

Файл успешно загружен в формате .m4a, но мне нужен mp3-файл.Я уже изменяю расширение файла .m4a на .mp3, но этот файл не воспроизводится.

Я пробовал множество близких примеров, но мне не удалось решить эту проблему.

Как я могу это сделать?

 func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
    mediaPicker.dismiss(animated: true) {

        let item: MPMediaItem = mediaItemCollection.items[0]
        let pathURL: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
        if pathURL == nil {
            self.alert(message: "Sorry, the returned mediaItemCollection appeart to be empty")
            return
        }

        let song_Title = item.value(forProperty: MPMediaItemPropertyTitle) as! String
        let filename_song = song_Title.replacingOccurrences(of: " ", with: "_")

        // get file extension andmime type
        let str = pathURL!.absoluteString
        let str2 = str.replacingOccurrences( of : "ipod-library://item/item", with: "")
        let arr = str2.components(separatedBy: "?")
        var mimeType = arr[0]
        mimeType = mimeType.replacingOccurrences( of : ".", with: "")


        // Export the ipod library as .m4a file to local directory for remote upload
        let exportSession = AVAssetExportSession(asset: AVAsset(url: pathURL!), presetName: AVAssetExportPresetAppleM4A)
        exportSession?.shouldOptimizeForNetworkUse = true
        exportSession?.outputFileType = AVFileType.m4a
        exportSession?.metadata = AVAsset(url: pathURL!).metadata

        let documentURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let outputURL = documentURL.appendingPathComponent("\(filename_song).m4a")

        //Delete Existing file
        do {
            try FileManager.default.removeItem(at: outputURL)
        } catch let error as NSError {
            print(error.debugDescription)
        }

        exportSession?.outputURL = outputURL
        exportSession?.exportAsynchronously(completionHandler: { () -> Void in

            if (exportSession!.status == AVAssetExportSession.Status.completed)
            {
                print("AV export succeeded.")
                self.alert(message: "File download successfully")

                do {

                    let newURL = outputURL.deletingPathExtension().appendingPathExtension("mp3")
                    let str = try FileManager.default.moveItem(at: outputURL, to: newURL)

                    print(str)
                } catch {
                    print("The file could not be loaded")
                }
            }
            else if (exportSession!.status == AVAssetExportSession.Status.cancelled)
            {
                print("AV export cancelled.")
            }
            else
            {
                print("AV export failed with error:- ", exportSession!.error!.localizedDescription)
            }

        })

    }
}
...