读取外部音频图片
一、加载图片
1.WebRequest加载
IEnumerator WebRequestLoadTexture(string Path)
{
UnityWebRequest _unityWebRequest = new UnityWebRequest(Path);
DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
_unityWebRequest.downloadHandler = texDl;
yield return _unityWebRequest.SendWebRequest();
//加载出来的图片分辨率
int width = 1920;
int high = 1080;
if (_unityWebRequest.isHttpError || _unityWebRequest.isNetworkError)
{
//如果加载报错,打印出错误
Debug.Log(_unityWebRequest.error);
}
else
{
Texture2D tex = new Texture2D(width, high);
tex = texDl.texture;
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
}
}
2.WWW加载(已弃用但还能用)
IEnumerator WWWLoadTexture(string Path)
{
WWW www = new WWW(Path);
yield return www;
if (www.error != null)
{
//如果加载报错,打印出错误
Debug.Log(www.error);
}
else
{
//加载图片
//获取Texture
Texture2D texture = www.texture;
//创建Sprite,texture.width, texture.height则是加载图片的对应分辨率
image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
3.传统IO方式
private void LoadByIO(string Path)
{
//创建文件读取流
FileStream fileStream = new FileStream(Path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
//创建文件长度缓冲区
byte[] bytes = new byte[fileStream.Length];
//读取文件
fileStream.Read(bytes, 0, (int)fileStream.Length);
//释放文件读取流
fileStream.Close();
fileStream.Dispose();
fileStream = null;
//创建Texture
int width = 1920;
int height = 1080;
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
//创建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
}
一、加载音频
1.WebRequest加载
IEnumerator WebRequestLoadClip(string Path)
{
//mp3貌似不行,AudioType对应格式,这里是WAV格式
UnityWebRequest _unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(Path, AudioType.WAV);
yield return _unityWebRequest.SendWebRequest();
if (_unityWebRequest.isHttpError || _unityWebRequest.isNetworkError)
{
//如果加载报错,打印出错误
Debug.Log(_unityWebRequest.error);
}
else
{
audioSource.clip = DownloadHandlerAudioClip.GetContent(_unityWebRequest);
}
audioSource.Play();
}
2.WWW加载(已弃用但还能用)
IEnumerator WWWLoadClip(string Path)
{
WWW www = new WWW(Path);
yield return www;
if (www.error != null)
{
//如果加载报错,打印出错误
Debug.Log(www.error);
}
else
{
//加载音乐
//WAV可以,mp3貌似加载不了(MP3 PC端不行,安卓上却可以)
audioSource.clip = www.GetAudioClip();
audioSource.Play();
}
}
提示:WWW和WebRequest在PC端貌似没法加载MP3,但安卓可以。
要用MP3的可参考这
同时别忘了安卓要多加"jar:file://",以StreamingAssets文件夹为例:“jar:file://” + Application.dataPath + “!/assets/”+“1.mp3”
U盘SD卡这些则加:“file://”——(例如地址:“file://”+"/mnt/sdcard/0.mp3")