0

我正在使用 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;

然后声音工作正常,但这是一个黑客,对吧?当然我做错了什么,但我不知道是什么。

谢谢你的时间。

4

1 回答 1

0

如果我没记错的话,每个 16 位样本将有 2 个字节,因此您的缓冲区字节数将是样本数的两倍。

于 2011-12-17T11:29:51.663 回答