我是靠谱客的博主 无辜银耳汤,最近开发中收集的这篇文章主要介绍Unity加载资源文件夹中的图片和视频并显示一、显示图片 二、显示视频 AVPro Video插件,简单好用功能强,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、显示图片 

法一:IO法

法二:WWW法 (网络文件)

//转载自https://www.cnblogs.com/guoguoguo/p/7350547.html

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

public class readPictures : MonoBehaviour
{

        string streamingPath = Application.streamingAssetsPath;
        string ContentData1 = Application.streamingAssetsPath + "\" + "data1.txt";
    private Image image;
    private string loadpath = "D:/SOmeOther/NGUI/Assets/StreamingAssets/test.jpg"; //IO方式加载的路径
    private string picpathWWW = "test.jpg"; //WWW的加载方式路径

    // Use this for initialization
    private void Start()
    {
        image = GetComponent<Image>();
        //IO方法加载速度快
//        LoadByIO();
        //WWW 加载速度慢
        LoadByWWW();

    }

    private void LoadByIO()
    {
        double startTime = (double) Time.time;
        //创建文件流
        FileStream fileStream = new FileStream(loadpath, FileMode.Open, FileAccess.Read);
        fileStream.Seek(0, SeekOrigin.Begin);
        //创建文件长度的缓冲区
        byte[] bytes = new byte[fileStream.Length];
        //读取文件
        fileStream.Read(bytes, 0, (int) fileStream.Length);
        //释放文件读取liu
        fileStream.Close();
        fileStream.Dispose();
        fileStream = null;

        //创建Texture
        int width = 300;
        int height = 372;
        Texture2D texture2D = new Texture2D(width, height);
        texture2D.LoadImage(bytes);

        Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),
            new Vector2(0.5f, 0.5f));
        image.sprite = sprite;
        double time = (double) Time.time - startTime;
        Debug.Log("IO加载用时:" + time);
    }


    private void LoadByWWW()
    {
        StartCoroutine(Load());
    }


    private string url = "file://D:/SOmeOther/NGUI/Assets/StreamingAssets/";
//    private string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502532130856&di=7135149ed906483861efdfc9770def3b&imgtype=0&src=http%3A%2F%2Fwww.newasp.net%2Fattachment%2Fsoft%2F2017%2F0811%2F144057_83971519.png"; 这里当然可以换做网络图片的URL 就加载网络图片了
    private IEnumerator Load()
    {
        double startTime = (double) Time.time;

        WWW www = new WWW(url + picpathWWW);//只能放URL
//        WWW www = new WWW(url);//只能放URL 这里可以换做网络的URL
        yield return www;
        if (www!=null && string.IsNullOrEmpty(www.error))
        {

            Texture2D texture = www.texture;
            //创建 Sprite
            Sprite sprite = Sprite.Create(texture,new Rect(0,0,texture.width,texture.height),new Vector2(0.5f,0.5f) );

            image.sprite = sprite;
            double time = (double)Time.time - startTime;
            Debug.Log("WWW加载用时:" + time);
        }
    }


}

法三:读取指定文件夹下的图片,并转换为sprite,然后再显示在UI上

    public Image image;
    privatestring _Path = Application.streamingAssetsPath + "/";//图片地址
    privatestring _texname = "DLAM.jpg";//图片名字
    private Texture2D m_Tex;

    void Start()
    {
        //加载
        LoadImageFile(_Path, _texname);
        //变换格式(图片变为sprite格式)
        Sprite tempSprite = Sprite.Create(m_Tex, new Rect(0, 0, m_Tex.width, m_Tex.height), new Vector2(10, 10));
        image.sprite = tempSprite;//赋值
    }
    private void LoadImageFile(string path, string _name)
    {
        m_Tex = new Texture2D(1, 1);
        m_Tex.LoadImage(ReadImage(path + _name));
    }
    private byte[] ReadImage(string path)
    {
        //文件流读取文件
        FileStream fileStream = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read);
        fileStream.Seek(0, SeekOrigin.Begin);
        byte[] binary = new byte[fileStream.Length]; //创建文件长度的buffer
        fileStream.Read(binary, 0, (int)fileStream.Length);
        fileStream.Close();
        fileStream.Dispose();
        fileStream = null;
        return binary;
    }

 

二、显示视频 

AVPro Video插件,简单好用功能强

常用功能

//转载自https://www.cnblogs.com/mrmocha/p/8087389.html
/*************************************************
 * 项目名称:Unity实现视频播放功能
 * 脚本创建人:魔卡
 * 脚本创建时间:2017.12.21
 * 脚本功能:控制视频播放类
 * ***********************************************/
using System.Collections;
using System.Collections.Generic;
using RenderHeads.Media.AVProVideo;
using UnityEngine;
using UnityEngine.UI;

//控制视频播放类
public class VideoController : MonoBehaviour
{
    //持有控制视频播放的组件
    public MediaPlayer mediaPlayer;

    //持有播放暂停切换开关
    public Toggle m_videoToggle;

    //持有是否循环播放开关
    public Toggle m_loopToggle;

    //持有控制播放速度滚动条
    public Slider m_playSpeedSlider;
    //持有控制播放速度的下拉列表
    public Dropdown m_playSpeedDropdown;

    //持有控制视频播放进度的进度条
    public Slider m_processSlider;

    //持有显示当前播放与总播放的时间显示
    public Text m_videoTimeTex;

    //持有返回几秒前按钮
    public Button m_backSecondsBtn;
    //设置每次点击返回的秒数
    private float m_backSeconds = 3f;

    //持有控制音量的Slider
    public Slider m_volumeSlider;
    //持有静音开关
    public Toggle m_muteToggle;
    //存储静音状态前用户设置的音量
    private float m_customVolume;

    void Awake()
    {
        //初始化
        //注册播放暂停开关事件
        m_videoToggle.onValueChanged.AddListener(DoPlayOrPause);
        //注册是否循环播放开关事件
        m_loopToggle.onValueChanged.AddListener(DoSetLoop);
        //注册控制速度的滚动天触发事件
        m_playSpeedSlider.onValueChanged.AddListener(DoChangeSpeed);

        //添加下拉列表选项
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "+4"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "+3"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "+2"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "+1"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "+0"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "-1"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "-2"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "-3"));
        m_playSpeedDropdown.options.Add(new Dropdown.OptionData( "-4"));
        //设置初始速度显示值
        m_playSpeedDropdown.value = 3;
        m_playSpeedDropdown.captionText.text = m_playSpeedDropdown.options[3].text;
        //注册控制速度的下拉列表触发事件
        m_playSpeedDropdown.onValueChanged.AddListener(DoChangeSpeed);

        //注册视频播放进度条值改变触发事件
        m_processSlider.onValueChanged.AddListener(OnProcessSliderChange);

        //注册返回1几秒前按钮触发事件
        m_backSecondsBtn.onClick.AddListener(OnBackSecondsClick);

        //注册音量Slider事件
        m_volumeSlider.onValueChanged.AddListener(OnVolumeSliderChange);
        //注册静音开关事件
        m_muteToggle.onValueChanged.AddListener(OnMuteToggleClick);

        //注册视频播放触发事件
        mediaPlayer.Events.AddListener(MediaEventHandler);
    }

    /// <summary>
    /// 视频播放时间触发
    /// </summary>
    /// <param name="arg0"></param>
    /// <param name="arg1"></param>
    /// <param name="arg2"></param>
    private void MediaEventHandler(MediaPlayer arg0, MediaPlayerEvent.EventType arg1, ErrorCode arg2)
    {
        switch (arg1)
        {
            case MediaPlayerEvent .EventType .Closing :
                Debug.Log("关闭播放器触发");
                break;
            case MediaPlayerEvent .EventType .Error :
                Debug.Log("报错误时触发");
                break;
            case MediaPlayerEvent .EventType .FinishedPlaying ://注意:如果视频设置为循环播放模式,则不触发此项
                Debug.Log("播放完成触发");
                break;
            case MediaPlayerEvent .EventType .FirstFrameReady :
                Debug.Log("准备完触发");
                break;
            case MediaPlayerEvent.EventType.MetaDataReady:
                Debug.Log("媒体数据准备准备中触发");
                break;
            case MediaPlayerEvent .EventType .ReadyToPlay :
                Debug.Log("准备去播放触发");
                break;
            case MediaPlayerEvent .EventType .Started ://注意:每暂停之后的开始播放都会触发一次
                Debug.Log("开始播放触发");
                break;
            default :
                Debug.Assert(false);
                break;
        }
    }

    void Start ()
    {
        LoadVideo();

        //初始化触发一次(同步声音大小)
        OnVolumeSliderChange(m_volumeSlider .value);
    }

    void Update()
    {
        //时刻更新播放进度方法
        DoUpdateVideoProcess();

        //时刻更新播放时间显示方法
        UpdateTimeText();
    }

    /// <summary>
    /// 加载视频方法
    /// </summary>
    void LoadVideo()
    {
        //通过插件中的方法加载(参数为:1.加载路径格式(与面板上相对应)2.加载的文件名 3.默认是否开始播放)
        mediaPlayer.OpenVideoFromFile(MediaPlayer.FileLocation.RelativeToStreamingAssetsFolder, "BigBuckBunny_360p30.mp4", false);
    }
    /// <summary>
    /// 播放与暂停开关点击触发
    /// </summary>
    /// <param name="s_isOn"></param>
    void DoPlayOrPause(bool s_isOn)
    {
        //如果播放,开始播放并文字显示“播放”
        if (s_isOn)
        {
            //通过持有的MediaPlayer类进行操控
            mediaPlayer.Control.Play();
            //更改播放开关显示的文字
            m_videoToggle.transform.Find("VideoText").GetComponent<Text>().text = "暂停";
        }
            //否则,暂停
        else
        {
            mediaPlayer.Control.Pause();
            //更改播放开关显示的文字
            m_videoToggle.transform.Find("VideoText").GetComponent<Text>().text = "播放";
        }
    }
    /// <summary>
    /// 是否循环播放开关点击触发
    /// </summary>
    /// <param name="s_isOn"></param>
    void DoSetLoop(bool s_isOn)
    {
        //通过持有的MediaPlayer类进行操控
        mediaPlayer.Control.SetLooping(s_isOn);
    }
    /// <summary>
    /// 改变播放速度方法(正的加速放映,负的倒放映)
    /// </summary>
    void DoChangeSpeed(float s_speed)//滑动条数值
    {
        //有部分瑕疵(正序倒序放调节过快反应会迟缓,与电脑配置有关)
        mediaPlayer.Control.SetPlaybackRate(s_speed);
    }
    /// <summary>
    /// 改变播放速度方法(正的加速放映,负的倒放映)
    /// </summary>
    void DoChangeSpeed(int s_speed)//下拉列表对应索引值
    {
        int tSpeed = 1;
        switch (s_speed)
        {
            case 0:
                tSpeed = 4;
                break;
            case 1:
                tSpeed = 3;
                break;
            case 2:
                tSpeed = 2;
                break;
            case 3:
                tSpeed = 1;
                break;
            case 4:
                tSpeed = 0;
                break;
            case 5:
                tSpeed = -1;
                break;
            case 6:
                tSpeed = -2;
                break;
            case 7:
                tSpeed = -3;
                break;
            case 8:
                tSpeed = -4;
                break;
            default :
                Debug.Assert(false);
                break;
        }
        //有部分瑕疵(正序倒序放调节过快反应会迟缓,与电脑配置有关)
        mediaPlayer.Control.SetPlaybackRate(tSpeed);
    }

    /// <summary>
    /// 时刻更新视频进度到滑动条上
    /// </summary>
    void DoUpdateVideoProcess()
    {
        //获取当前播放时长
        float tCurrentTime = mediaPlayer.Control.GetCurrentTimeMs();
        //获取视频总长度
        float tVideoTime = mediaPlayer.Info.GetDurationMs();
        //计算出对应的播放进度赋值给显示播放进度的进度条
        m_processSlider.value = tCurrentTime/tVideoTime;
    }

    /// <summary>
    /// 更新播放进度的时间显示
    /// </summary>
    void UpdateTimeText()
    {
        //对当前播放时间转换时间格式
        //转化为 秒
        int tCurrentSeconds = (int)mediaPlayer.Control.GetCurrentTimeMs()/1000;
        //获取当前分数
        int tCurrentMin = tCurrentSeconds/60;
        //重新赋值剩余多少秒
        tCurrentSeconds = tCurrentSeconds%60;
        string tCurrentSecondStr = tCurrentSeconds < 10 ? "0" + tCurrentSeconds : tCurrentSeconds.ToString();

        //对总时间转化时间格式
        //转化为秒
        int tVideoTimeSeconds = (int) mediaPlayer.Info.GetDurationMs()/1000;
        //获取总的分数
        int tVideoTimeMin = tVideoTimeSeconds/60;
        //重新复制剩余多少秒
        tVideoTimeSeconds = tVideoTimeSeconds%60;
        string tVideoTimeSecondStr = tVideoTimeSeconds < 10 ? "0" + tVideoTimeSeconds : tVideoTimeSeconds.ToString();

        //拼接一下时间显示字符串
        string tTime = string.Format("<color=red>{0}:{1}/{2}:{3}</color>", tCurrentMin, tCurrentSecondStr, tVideoTimeMin, tVideoTimeSecondStr);
        //string tTime = string.Format("<b>{0}:{1}/{2}:{3}</b>", tCurrentMin, tCurrentSeconds, tVideoTimeMin, tVideoTimeSeconds);
        //string tTime = string.Format("<i>{0}:{1}/{2}:{3}</i>", tCurrentMin, tCurrentSeconds, tVideoTimeMin, tVideoTimeSeconds);

        m_videoTimeTex.text =  tTime ;;
    }

    /// <summary>
    /// 视频播放进度条值改变触发
    /// </summary>
    /// <param name="value"></param>
    void OnProcessSliderChange(float value)
    {
        //获取视频总长度
        float tVideoTime = mediaPlayer.Info.GetDurationMs();
        //当前视频的时间
        float tCurrentTime = m_processSlider.value*tVideoTime;
        //将视频时间调到对应的节点
        mediaPlayer.Control.Seek(tCurrentTime);
    }


    /// <summary>
    /// 播放进度条开始拖动触发(EventTrigger触发)
    /// </summary>
    public void OnProcessSliderDragBegin()
    {
        //暂停播放
        mediaPlayer.Control.Pause();
    }

    /// <summary>
    /// 播放进度条结束拖动触发(EventTrigger触发)
    /// </summary>
    public void OnProcessSliderDragEnd()
    {
        //开始播放
        mediaPlayer.Control.Play();
    }


    /// <summary>
    /// 返回到几秒之前方法
    /// </summary>
    void OnBackSecondsClick()
    {
        //获取当前播放进度时间
        float tCurrentTime = mediaPlayer.Control.GetCurrentTimeMs();

        //10s前进度时间(如果存在前十秒则退,不存在还是当前时间进度)
        tCurrentTime = (tCurrentTime - m_backSeconds * 1000) >= 0 ? tCurrentTime - m_backSeconds*1000 : tCurrentTime;

        //设置进度时间
        mediaPlayer.Control.Seek(tCurrentTime);
    }

    /// <summary>
    /// 音量进度条改变触发
    /// </summary>
    /// <param name="value"></param>
    void OnVolumeSliderChange(float value)
    {
        //保存当前已经设置的音量
        if (value != 0)
        {
            m_customVolume = m_volumeSlider.value;
        }
        //设置音量
        mediaPlayer.Control.SetVolume(value);
        //如果音量手动调节到零,则将静音模式打开
        if (value > 0)
        {
            m_muteToggle.isOn = false;
        }
        else
        {
            m_muteToggle.isOn = true;
        }
    }

    /// <summary>
    /// 静音开关触发
    /// </summary>
    /// <param name="s_isOn"></param>
    void OnMuteToggleClick(bool s_isOn)
    {
        //如果静音
        if (s_isOn)
        {
            //设置静音
            m_volumeSlider.value = 0;
            mediaPlayer.Control.SetVolume(0);
        }
            //不静音
        else
        {
            m_volumeSlider.value = m_customVolume;
            mediaPlayer.Control.SetVolume(m_customVolume);
        }
    }
}

 

 

 

 

 

 

最后

以上就是无辜银耳汤为你收集整理的Unity加载资源文件夹中的图片和视频并显示一、显示图片 二、显示视频 AVPro Video插件,简单好用功能强的全部内容,希望文章能够帮你解决Unity加载资源文件夹中的图片和视频并显示一、显示图片 二、显示视频 AVPro Video插件,简单好用功能强所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部