xcode 如何从设备库中选择/浏览音频文件,如照片库?

gv8xihay  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(170)

我正在构建一个应用程序,用户可以选择(从库)或捕获(记录)图像/视频/音频。
我已经实现了视频和图像媒体和重新编码音频文件,但从库中访问音频时,其崩溃在下面的一行。它的工作正常,当我试图访问图像和视频文件从图书馆。
我认为这是因为音频文件没有存储在photoLibrary中,如果是这样,任何人都可以请告诉我如何才能访问/打开设备中的音频文件,以便用户可以选择。
//下面是我用来选择媒体(image/video/audio)的代码

- (void)selectingMediaFromLibraryOfType:(MEDIAUPLOADTYPE)mediaType {

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    switch (mediaType) {
    case mediaUploadTpeAudio:
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMP3, nil]; //crashing on this line
        break;

    case mediaUploadTpeImage:
        break;

    case mediaUploadTpeVideo:
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
        break;

    default:
        break;
    }

    [self presentViewController:picker animated:YES completion:NULL];
}

我已经做了同样的图像和视频,它的工作。
我还想知道当你从iOS传输/下载音频文件到iOS时文件存储在哪里。

chhkpiq4

chhkpiq41#

音频的媒体选取器不同于图像和视频。你必须使用MPMediaPickerController类。它的功能与UIImagePickerController类相同。
并执行MPMediaPickerControllerDelegate以获取所选文件。

jdgnovmf

jdgnovmf2#

您可以从UIDocumentPickerViewController中获取音频文件。
参考以下代码,

class MyViewController: UIViewController, UIDocumentPickerDelegate {
    var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    self.openDocumentPicker()
}

func openDocumentPicker() {
    var documentPicker: UIDocumentPickerViewController
    if #available(iOS 14.0, *) {
        let supportedTypes: [UTType] = [UTType.audio]
        documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes)
    } else {
        documentPicker = UIDocumentPickerViewController(documentTypes: ["public.audio"], in: UIDocumentPickerMode.import)
    }
    documentPicker.delegate = self
    // set popover controller for iPad
    if let popoverController = documentPicker.popoverPresentationController {
        popoverController.sourceView = self.yourView //set your view name here
    }
    self.present(documentPicker, animated: true, completion: nil)
}

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let url = urls.first else { return }
    let _ = url.startAccessingSecurityScopedResource()
    let asset = AVURLAsset(url: url)
    guard asset.isComposable else {
        print("Your music is Not Composible")
        return
    }
    addAudio(audioUrl: url)
}

func addAudio(audioUrl: URL) {
    // lets create your destination file url
    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    print(destinationUrl)
    
    // to check if it exists before downloading it
    if FileManager.default.fileExists(atPath: destinationUrl.path) {
        print("The file already exists at path")
        self.playMusic(url: destinationUrl)
    } else {
        // if the file doesn't exist you can use NSURLSession.sharedSession to download the data asynchronously
        print("Downloading...")
        URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
            guard let location = location, error == nil else { return }
            do {
                // after downloading your file you need to move it to your destination url
                try FileManager.default.moveItem(at: location, to: destinationUrl)
                self.playMusic(url: destinationUrl)
                
                print("File moved to documents folder")
            } catch let error as NSError {
                print(error.localizedDescription)
                
            }
        }).resume()
    }
}

func playMusic(url: URL) {
    if audioPlayer.isPlaying {
        audioPlayer.pause()
    } else {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()
            let isplay = audioPlayer.play()
            print(isplay)
        } catch let error {
            print(error.localizedDescription)
        }
    }
}
}

相关问题