0

DirectSoundを使用して、オーディオカードに正弦波を書き込みます。サンプルサイズは16ビット、1チャネルです。私の質問は、5秒の音を出すのに何サンプルかかるべきかということです。サンプルレートは毎秒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バイトになるので、バッファのバイト数はサンプル数の2倍になります。

于 2011-12-17T11:29:51.663 に答える