You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 dataTs to 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 .ts extension because your data variable is named dataTs—make sure to change this to match the actual format of your video data (e.g., .mp4, .mov) if needed.
  • Using UUID().uuidString ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:52:03