DirectSound Timing和sample-count
我正在使用DirectSound将正弦波写入声卡。样本大小为16位,一个通道。我的问题是,需要多少样本才能发出五秒钟的声音?采样率为每秒44100个样本。数学很简单:220500就是答案。然而,这让我很疯狂,因为我的代码只播放了大约一半的时间!这是我的代码:
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);
}
}
}
根据我的计算,这应该发挥5秒。它上场时间很长。如果我改变
int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels;
至
int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels
* waveFormat.BlockAlign;
然后声音工作正常,但这是一个黑客,对吧?当然我做错了什么,但我不知道是什么。
谢谢你的时间。
没有找到相关结果
已邀请:
1 个回复
恋裂