static List<Byte> CreateSaw(int frequency) { var sampleRate = 16000; // var frequency = 500; var amplitude = 0.2; var seconds = 1; var raw = new byte[sampleRate * seconds * 2]; // stereo var multiple = 2.0 * frequency / sampleRate; for (int n = 0; n < sampleRate * seconds; n++) { var sampleSaw = ((n * multiple) % 2) - 1; var sampleValue = sampleSaw > 0 ? amplitude : -amplitude; var sample = (short)(sampleValue * Int16.MaxValue); var bytes = BitConverter.GetBytes(sample); raw[n * 2] = bytes[0]; // left raw[n * 2 + 1] = bytes[1]; // right } return raw.ToList(); },这段代码中,raw数据是如何保存的
时间: 2024-02-10 09:20:55 浏览: 28
这段代码中,raw数据以字节列表(List<Byte>)的形式保存。具体来说,在这段代码中,raw是一个长度为sampleRate * seconds * 2的byte数组(其中sampleRate为采样率,即每秒采样的次数,seconds为音频的时长),它被初始化为全0。接着,对于每个采样点,都会计算出对应的采样值sample,并将其转换为2个字节的数据。最后,将这些字节依次存储到raw列表中,其中左右声道的数据被交替存储。因此,raw列表中的每个元素都是一个字节,对应着音频数据中的一个采样点。
相关问题
static List<Byte> CreateSaw(int frequency) { var sampleRate = 16000; // var frequency = 500; var amplitude = 0.2; var seconds = 1; var raw = new byte[sampleRate * seconds * 2]; // stereo var multiple = 2.0 * frequency / sampleRate; for (int n = 0; n < sampleRate * seconds; n++) { var sampleSaw = ((n * multiple) % 2) - 1; var sampleValue = sampleSaw > 0 ? amplitude : -amplitude; var sample = (short)(sampleValue * Int16.MaxValue); var bytes = BitConverter.GetBytes(sample); raw[n * 2] = bytes[0]; // left raw[n * 2 + 1] = bytes[1]; // right } return raw.ToList(); },把这段代码改成生成正弦波
可以将CreateSaw函数中的sampleSaw计算方式改为:
var sampleSine = Math.Sin(2 * Math.PI * frequency * n / sampleRate);
同时将函数名由CreateSaw改为CreateSine,完整的代码如下:
static List<Byte> CreateSine(int frequency)
{
var sampleRate = 16000;
var amplitude = 0.2;
var seconds = 1;
var raw = new byte[sampleRate * seconds * 2]; // stereo
for (int n = 0; n < sampleRate * seconds; n++)
{
var sampleSine = Math.Sin(2 * Math.PI * frequency * n / sampleRate);
var sampleValue = amplitude * sampleSine;
var sample = (short)(sampleValue * Int16.MaxValue);
var bytes = BitConverter.GetBytes(sample);
raw[n * 2] = bytes[0]; // left
raw[n * 2 + 1] = bytes[1]; // right
}
return raw.ToList();
}
阅读全文