分割音频波形精灵,其宽度超出滚动矩形的范围



我是Unity 3D的新手,正在尝试拆分Scroll Rect中包含音频波形的texture2D精灵。波形来自用户导入的音频源,并像时间线一样水平添加到滚动矩形中。创建波形的脚本可以工作,但宽度的变量(来自另一个脚本,但这不是问题所在(超过了Texture2D的限制,只有当我手动设置小于16000的宽度时,波形才会出现,但不会达到滚动矩形的最大值。通常,一首3-4分钟的歌曲的宽度为55000-60000,这是无法渲染的。我需要将波形纹理2D精灵水平拆分为多个部分(或Childs(,并仅在出现在屏幕上时进行渲染。我该怎么做?提前谢谢。

这将创建波形精灵,并应将精灵拆分为多个精灵并水平放置在一起,仅当它们出现在屏幕上时渲染(:

public void LoadWaveform(AudioClip clip)
{
Texture2D texwav = waveformSprite.GetWaveform(clip);
Rect rect = new Rect(Vector2.zero, new Vector2(Realwidth, 180));
waveformImage.sprite = Sprite.Create(texwav, rect, Vector2.zero);
waveformImage.SetNativeSize();
}

这创建了来自音频剪辑的波形(从互联网上获取并为我的项目进行修改(:

public class WaveformSprite : MonoBehaviour
{
private int width = 16000; //This should be the variable from another script
private int height = 180;
public Color background = Color.black;
public Color foreground = Color.yellow;
private int samplesize;
private float[] samples = null;
private float[] waveform = null;
private float arrowoffsetx;
public Texture2D GetWaveform(AudioClip clip)
{
int halfheight = height / 2;
float heightscale = (float)height * 0.75f;
// get the sound data
Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
waveform = new float[width];
Debug.Log("NUMERO DE SAMPLES: " + clip.samples);
var clipSamples = clip.samples;
samplesize = clipSamples * clip.channels;
samples = new float[samplesize];
clip.GetData(samples, 0);
int packsize = (samplesize / width);
for (int w = 0; w < width; w++)
{
waveform[w] = Mathf.Abs(samples[w * packsize]);
}
// map the sound data to texture
// 1 - clear
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tex.SetPixel(x, y, background);
}
}
// 2 - plot
for (int x = 0; x < width; x++)
{
for (int y = 0; y < waveform[x] * heightscale; y++)
{
tex.SetPixel(x, halfheight + y, foreground);
tex.SetPixel(x, halfheight - y, foreground);
}
}
tex.Apply();
return tex;
}

}

与其在一个循环中读取所有样本以填充波形[],不如只读取当前纹理所需的量(利用偏移量跟踪阵列中的位置(。

计算函数将输出的纹理数量。

var textureCount = Mathf.CeilToInt(totalWidth / maxTextureWidth); // max texture width 16,000

创建一个外循环以生成每个纹理。

for (int i = 0; i < textureCount; i++)

计算当前纹理宽度(用于波形阵列和绘制循环(。

var textureWidth = Mathf.CeilToInt(Mathf.Min(totalWidth - (maxTextureWidth * i), maxWidth));

利用偏移量来填充波形阵列。

for (int w = 0; w < textureWidth; w++)
{
waveform[w] = Mathf.Abs(samples[(w + offset) * packSize]);
}

偏移量在纹理循环结束时增加该纹理使用的采样数(即纹理宽度(。

offset += textureWidth;

最后,函数将返回一个Texture2d数组,而不是一个。

最新更新