您的位置:首页 > 移动开发 > Unity3D

【Unity开发】简单的Wav文件压缩

2016-01-15 21:49 495 查看
using UnityEngine;
using System.Collections;
using System.Text;
using System.IO;
using System;
using System.Collections.Generic;
public class audioTest : MonoBehaviour {

void Start () {

//采样率
byte[] samplingRate = new byte[4];
byte[] tempSR = new byte[4];
//传输速度
byte[] speed = new byte[4];
byte[] tempSpeed = new byte[4];
//DATA长度
byte[] length = new byte[4];
byte[] tempLenth = new byte[4];

byte[] source = new byte[24];
byte[] mid = new byte[8];

FileStream fs = new FileStream(Application.dataPath + @"\test.wav", FileMode.Open, FileAccess.Read);
// fs.Position = dataPosition;
BinaryReader br = new BinaryReader(fs);
br.Read(source, 0, 24);
br.Read(samplingRate, 0, 4);
int temp = System.BitConverter.ToInt32(samplingRate, 0);
tempSR = System.BitConverter.GetBytes(temp / 2);
br.Read(speed, 0, 4);
temp = System.BitConverter.ToInt32(speed, 0);
tempSpeed = System.BitConverter.GetBytes(temp / 2);
br.Read(mid, 0, 8);
br.Read(length, 0, 4);
temp = System.BitConverter.ToInt32(length,0);
tempLenth = System.BitConverter.GetBytes(temp /2);

byte[] content = new byte[getHexToInt(length)];
byte[] sample = new byte[(content.Length)/2];
br.Read(content, 0, content.Length);
getHex(content);
sample = getSample(content);

using (FileStream fs1 = new FileStream(Application.dataPath + @"\data.wav", FileMode.Create))
{
BinaryWriter bw = new BinaryWriter(fs1);
foreach (byte i in source)
{
bw.Flush();
bw.Write(i);
}
foreach (byte i in tempSR)
{
bw.Flush();
bw.Write(i);
}

foreach (byte i in tempSpeed)
{
bw.Flush();
bw.Write(i);
}
foreach (byte i in mid)
{
bw.Flush();
bw.Write(i);
}
foreach (byte i in tempLenth)
{
bw.Flush();
bw.Write(i);
}
foreach (byte i in sample)
{
bw.Flush();
bw.Write(i);
}

bw.Close();
fs1.Close();
}
}

/// <summary>
/// 通过头 计算DATA大小
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
static int getHexToInt(byte[] x)
{
string retValue = "";
for (int i = x.Length - 1; i >= 0; i--)
{
retValue += x[i].ToString("X");
}
//180FA50   即10进制DATA大小
print(retValue);

return Convert.ToInt32(retValue, 16);
}
/// <summary>
/// 将字符串转化为16进制字节
/// </summary>
/// <param name="x"></param>
static void getHex(byte[] x)
{
byte tmp;
for (int i = 0; i < x.Length; i++)
{
tmp = Convert.ToByte(x[i].ToString("X"), 16);
x[i] = tmp;
}
}

static byte[] getSample(byte[] x)
{
byte[] retValue = new byte[x.Length];
byte[] temp = new byte[retValue.Length/2 ];

for (int i = 0; i < retValue.Length; i++)
{

retValue[i] += x[i];

}
for (int i = 0; i < retValue.Length/2; i++)
{
temp[(i)] = retValue[(2*i+1)];
}
return temp;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: