Music_Player3/relax.offline.mp3.music/MP/MPSideA/ViewControllers/Add(新增资源)/MPSideA_AddViewController.swift
2024-06-03 09:48:39 +08:00

214 lines
9.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// AddViewController.swift
// MusicPlayer
//
// Created by Mr.Zhou on 2024/3/27.
//
import UIKit
import AVFoundation
import Photos
class MPSideA_AddViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//
view.layer.masksToBounds = true
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
view.layer.cornerRadius = 18*width
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.notificationKey.add(observer: self, selector: #selector(successfullCreateAction), notificationName: .sideA_creat_music)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
//
@IBAction func action1Click(_ sender: UIButton) {
getVideo()
}
//
@IBAction func action2Click(_ sender: UIButton) {
var documentPicker:UIDocumentPickerViewController?
if #available(iOS 14, *) {
//访
documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.mp3,.mpeg4Movie,.mpeg4Audio, .audio, .movie], asCopy: false)
}else {
//()
let types:[String] = ["public.movie","public.audio"]
// UIDocumentPickerViewController
documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .open)
}
documentPicker!.delegate = self
documentPicker!.modalPresentationStyle = .formSheet
//
present(documentPicker!, animated: true)
}
//
private func createMusic(_ title:String, duration:Double, cover:UIImage, url:URL) {
///
let number = Int(arc4random_uniform(8999) + 1000)
let path = "\(number)\(Date().timeZone().toString(.custom("HH:mm:ss-MMMdd-YYYY")))\(title)"
//
let videoSaveUrl = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!).appendingPathComponent(path).path
let urlAsset = AVURLAsset(url:url)
let session = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetHighestQuality)
session?.outputURL = URL(fileURLWithPath: videoSaveUrl)
session?.outputFileType = .mp4
session?.exportAsynchronously(completionHandler: {
let exportState = session?.status
switch exportState{
case .failed:
print("Export Failed:\(String(describing: session?.error))")
break
case .completed:
//
print("Export Complete")
break
default:
break
}
})
//
let music = MPSideA_MusicModel.create()
music.identifier = Date().timeZone().toString(.custom("HH:mm:ss/MM-dd/YYYY"))
//
music.title = title
music.duration = duration
music.cover = cover.pngData()!
music.isLocal = false
music.path = path
music.creationTime = Date().timeZone()
music.lastTime = nil
MPSideA_MusicModel.save()
print("Resources have been successfully accessed")
}
@objc private func successfullCreateAction() {
DispatchQueue.main.async {
[weak self] in
self?.dismiss(animated: true)
}
}
}
//MARK: -
extension MPSideA_AddViewController: UIImagePickerControllerDelegate & UINavigationControllerDelegate, UIDocumentPickerDelegate {
//
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true) {
print("Failure to complete selection event")
}
}
//
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true) {[weak self] in
let videoUrl = info[.mediaURL] as! URL
print(videoUrl)
//
let asset = AVURLAsset(url: videoUrl, options: nil)
print("Select the real path of the file\(videoUrl)")
let data = self?.setPathToData(videoUrl, asset: asset)
self?.createMusic(data!.2, duration: data!.0, cover: data!.1, url: videoUrl)
NotificationCenter.notificationKey.post(notificationName: .sideA_creat_music)
// //
// picker.dismiss(animated: true) {
// [weak self] in
// //
// guard let passet = info[.phAsset] as? PHAsset else {
// print("Selected resources failed to load")
// return
// }
// //
// let options:PHVideoRequestOptions = .init()
// //
// options.version = .original
// options.deliveryMode = .automatic
// //访
//// options.isNetworkAccessAllowed = true
// PHImageManager.default().requestAVAsset(forVideo: passet, options: options) { [weak self] (asset, audioMix, info) in
// var videoUrl:URL?
// guard let urlAsset = asset as? AVURLAsset else {
// print("Selected resources failed to load")
// return
// }
// videoUrl = urlAsset.url as URL
// print("Select the real path of the file\(videoUrl!)")
// let data = self?.setPathToData(videoUrl!, asset: urlAsset)
// self?.createMusic(data!.2, duration: data!.0, cover: data!.1, path: videoUrl!)
// NotificationCenter.notificationKey.post(notificationName: .creat_music)
// }
// }
}
}
//
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let selectedFileURL = urls.first else {
return
}
progressData(selectedFileURL)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
//
print("Failure to complete selection event")
}
//
private func progressData(_ url:URL) {
//访
let authozied = url.startAccessingSecurityScopedResource()
if authozied == true {
//访
let fileCoordinator = NSFileCoordinator()
fileCoordinator.coordinate(readingItemAt: url, options: .withoutChanges, error: nil) { [weak self] (newUrl) in
//
print("Select the real path of the file\(newUrl)")
let data = self?.setPathToData(newUrl, asset: .init(url: newUrl))
self?.createMusic(data!.2, duration: data!.0, cover: data!.1, url: newUrl)
NotificationCenter.notificationKey.post(notificationName: .sideA_creat_music)
}
}else {
print("Selected resources failed to load")
}
//访
url.stopAccessingSecurityScopedResource()
}
///
private func setPathToData(_ url:URL, asset:AVURLAsset) -> (TimeInterval,UIImage,String){
//
var duration:TimeInterval = 0
let time = asset.duration
// if #available(iOS 16, *) {
// do {
// time = try await asset.load(.duration)
// } catch {
// print("Conversion to time failed")
// }
// }else {
// time = asset.duration
// }
duration = CMTimeGetSeconds(time)
//
let gen = AVAssetImageGenerator(asset: asset)
gen.appliesPreferredTrackTransform = true
//
let firstTime = CMTimeMakeWithSeconds(0.0, preferredTimescale: 1)
var actualTime:CMTime = CMTimeMakeWithSeconds(0, preferredTimescale: 0)
var firstImage:UIImage!
do {
//
let image = try gen.copyCGImage(at: firstTime, actualTime: &actualTime)
firstImage = UIImage(cgImage: image)
} catch {
//
print("Failed to get file the first image")
//
firstImage = .init(named: "End Of Days")
}
//
let title:String = url.lastPathComponent
return (duration,firstImage,title)
}
}