如何在AVPlayer中用Data替代标准URL播放视频?
How to Play Video from Data in AVPlayer (Instead of URL)
Alright, so you've got a Data object (dataTs) instead of a remote URL and want to feed it into AVPlayer—totally get it. The catch is AVPlayer doesn't support direct initialization from Data out of the box, but we can work around this by writing the data to a temporary local file and using that file's URL instead. Here's how to adjust your code:
Step-by-Step Implementation
- First, create a unique temporary file URL in your app's cache directory (safe for temporary files, and the system can clean it up automatically if needed).
- Write your
dataTsto this temporary file. - Initialize AVPlayer with the local file URL, just like you would with a remote URL.
Full Code Example
// Create a unique temporary file URL in the cache directory guard let tempFileURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first? .appendingPathComponent("\(UUID().uuidString).ts") else { print("Failed to generate temporary file URL") return } do { // Write the Data to the temporary file try dataTs.write(to: tempFileURL) // Initialize AVPlayer with the local file URL let player = AVPlayer(url: tempFileURL) playerViewController.player = player // Optional: Start playback automatically player.play() } catch { print("Error handling video data: \(error.localizedDescription)") }
Key Notes
- I used the
.tsextension because your data variable is nameddataTs—make sure to change this to match the actual format of your video data (e.g.,.mp4,.mov) if needed. - Using
UUID().uuidStringensures the temporary file has a unique name, so you won't run into conflicts with existing files. - If you want to free up space after playback, you can manually delete the temporary file once you're done with the player:
if FileManager.default.fileExists(atPath: tempFileURL.path) { try? FileManager.default.removeItem(at: tempFileURL) }
内容的提问来源于stack exchange,提问作者Andrei Trotsko
相关产品推荐
相关产品推荐

