2017-03-06 54 views
1

我想在Unity中創建一個媒體播放器,它從靜態文件夾中讀取所有媒體文件並播放所有媒體(圖像靜態持續時間,視頻長度視頻)。首先,我試圖讓它與圖像一起工作。Unity從媒體文件夾加載媒體和在RawImage上顯示

我對Unity非常陌生,對C#不太好。我能夠將所有媒體文件源(圖像)獲取到數組中,但接下來我需要將它們轉換爲紋理並放置在RawImage組件上。我堅持這部分。

如果我有src(例如C:\ medias \ img1.jpg)那麼我怎樣才能把它作爲一個圖像放在RawImage組件上?

我的代碼 - >

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.UI; 
using UnityEditor; 
using System; 
using System.IO; 
using System.Linq; 

public class Player : MonoBehaviour { 

    // Use this for initialization 
    void Start() { 
     DirectoryInfo dir = new DirectoryInfo(@"C:\medias"); 
     string[] extensions = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ogg", ".OGG" }; 
     FileInfo[] info = dir.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray(); 
     Debug.Log (info[0]); 
     // Logs C:\medias\img1.jpg 
    } 

    // Update is called once per frame 
    void Update() { 

    } 
} 

謝謝:)

回答

3

首先我試圖讓它只圖像的工作。

我對Unity非常陌生,對C#不太好。我能夠將所有 媒體文件源(圖像)獲取到一個數組,但接下來我需要將它們轉換爲紋理並放置在RawImage組件上。我堅持與 這部分。

您在尋找Texture2D.LoadImage的功能。它將圖像字節轉換爲Texture2D,然後您可以將該Texture2D分配給RawImage。

您必須提出有關如何使用視頻完成此操作的新問題。這太複雜了。

public RawImage rawImage; 
Texture2D[] textures = null; 

//Search for files 
DirectoryInfo dir = new DirectoryInfo(@"C:\medias"); 
string[] extensions = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ogg", ".OGG" }; 
FileInfo[] info = dir.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray(); 

//Init Array 
textures = new Texture2D[info.Length]; 


for (int i = 0; i < info.Length; i++) 
{ 
    MemoryStream dest = new MemoryStream(); 

    //Read from each Image File 
    using (Stream source = info[i].OpenRead()) 
    { 
     byte[] buffer = new byte[2048]; 
     int bytesRead; 
     while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) 
     { 
      dest.Write(buffer, 0, bytesRead); 
     } 
    } 

    byte[] imageBytes = dest.ToArray(); 

    //Create new Texture2D 
    Texture2D tempTexture = new Texture2D(2, 2); 

    //Load the Image Byte to Texture2D 
    tempTexture.LoadImage(imageBytes); 

    //Put the Texture2D to the Array 
    textures[i] = tempTexture; 
} 

//Load to Rawmage? 
rawImage.texture = textures[0];