C# DirectSound定时和采样计数
我正在使用DirectSound向声卡写入正弦波。样本大小为16位,一个通道。我的问题是,发出五秒钟的声音需要多少样本?采样率为每秒44100个样本。数学很简单:答案是220500。但这让我发疯,因为我的代码只播放了大约一半的时间!!这是我的密码:C# DirectSound定时和采样计数,c#,directsound,C#,Directsound,我正在使用DirectSound向声卡写入正弦波。样本大小为16位,一个通道。我的问题是,发出五秒钟的声音需要多少样本?采样率为每秒44100个样本。数学很简单:答案是220500。但这让我发疯,因为我的代码只播放了大约一半的时间!!这是我的密码: using Microsoft.DirectX.DirectSound; using System; namespace Audio { // The class public class Oscillator {
using Microsoft.DirectX.DirectSound;
using System;
namespace Audio
{
// The class
public class Oscillator
{
static void Main(string[] args)
{
// Set up wave format
WaveFormat waveFormat = new WaveFormat();
waveFormat.FormatTag = WaveFormatTag.Pcm;
waveFormat.Channels = 1;
waveFormat.BitsPerSample = 16;
waveFormat.SamplesPerSecond = 44100;
waveFormat.BlockAlign = (short)(waveFormat.Channels * waveFormat.BitsPerSample / 8);
waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond;
// Set up buffer description
BufferDescription bufferDesc = new BufferDescription(waveFormat);
bufferDesc.Control3D = false;
bufferDesc.ControlEffects = false;
bufferDesc.ControlFrequency = true;
bufferDesc.ControlPan = true;
bufferDesc.ControlVolume = true;
bufferDesc.DeferLocation = true;
bufferDesc.GlobalFocus = true;
Device d = new Device();
d.SetCooperativeLevel(new System.Windows.Forms.Control(), CooperativeLevel.Priority);
int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels;
char[] buffer = new char[samples];
// Set buffer length
bufferDesc.BufferBytes = buffer.Length * waveFormat.BlockAlign;
// Set initial amplitude and frequency
double frequency = 500;
double amplitude = short.MaxValue / 3;
double two_pi = 2 * Math.PI;
// Iterate through time
for (int i = 0; i < buffer.Length; i++)
{
// Add to sine
buffer[i] = (char)(amplitude *
Math.Sin(i * two_pi * frequency / waveFormat.SamplesPerSecond));
}
SecondaryBuffer bufferSound = new SecondaryBuffer(bufferDesc, d);
bufferSound.Volume = (int)Volume.Max;
bufferSound.Write(0, buffer, LockFlag.None);
bufferSound.Play(0, BufferPlayFlags.Default);
System.Threading.Thread.Sleep(10000);
}
}
}
到
然后声音正常,但那是一种杂音,对吗?我肯定做错了什么,但我不知道是什么
谢谢您的时间。如果我没有弄错的话,您的16位每个样本将有2个字节,因此您的缓冲区字节数将是样本数的两倍。您的每个样本将有2个字节。这就是我使用字符而不是字节的原因。每个字符有2个字节,对吗?看来我应该用ushort来避免混乱!
int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels;
int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels
* waveFormat.BlockAlign;