如何从filePath播放和保存AudioFile iOS Swift

ogsagwnx  于 2023-05-19  发布在  iOS
关注(0)|答案(2)|浏览(136)

我从文件夹中选择音频文件,并在此委托函数中获取URL

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    print("url", url)
    self.filePickedBlock?(url)
}

Url看起来像这样
文件:///private/var/移动的/Containers/Data/Application/8012C1BB-43E3-4E0C-9167-B7B5A49824A1/tmp/com.ios.PrankYourFriends-Inbox/AUDIO1.m4a
我将此URL保存为Realm数据库中的字符串,并在我想要播放时获取它。

我面临的问题

当我选择后立即播放此音频时,它播放得很好。但是如果我转到任何其他ViewController并再次返回并按下播放按钮,它就不会播放音频。
我是这样播放音频的:

self.avPlayer = AVPlayer.init(url: filePath)
self.avPlayer?.play()

请让我知道我做错了什么。

mrfwxfqh

mrfwxfqh1#

tmp文件夹

/tmp/com.ios.PrankYourFriends-Inbox/AUDIO1.m4a

复制它说文件/图书馆然后使用它的任何时间

wf82jlnq

wf82jlnq2#

请参考我的答案https://stackoverflow.com/a/76259485/11851754
也就是说

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)
        }
    }
}
}

相关问题