WaveTone
類(假設您正在使用我剛剛搜索的其中一個類)可能會提供層出不窮的數據。如果您想限制輸出到特定的時間段,您需要將特定數量的數據加載到另一個緩衝區/流中,或者修改類別以停止生成超過持續時間的數據。
事情是這樣的:
class WaveTone : WaveStream
{
readonly WaveFormat Format;
public readonly double Frequency;
public readonly double Amplitude;
public readonly double Duration;
readonly long streamLength;
long pos;
const double timeIncr = 1/44100.0;
readonly double sinMult;
public WaveTone(double freq, double amp)
: this(freq, amp, 0)
{ }
public WaveTone(double freq, double amp, double dur)
{
Format = new WaveFormat(44100, 16, 1);
Frequency = freq;
Amplitude = Math.Min(1, Math.Max(0, amp));
Duration = dur;
streamLength = Duration == 0 ? long.MaxValue : (long)(44100 * 2 * Duration);
pos = 0;
sinMult = Math.PI * 2 * Frequency;
}
public override WaveFormat WaveFormat
{
get { return Format; }
}
public override long Length
{
get { return streamLength; }
}
public override long Position
{
get { return pos; }
set { pos = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (pos >= streamLength)
return 0;
int nSamples = count/2;
if ((pos + nSamples * 2) > streamLength)
nSamples = (int)(streamLength - pos)/2;
double time = pos/(44100 * 2.0);
int rc = 0;
for (int i = 0; i < nSamples; i++, time += timeIncr, ++rc, pos += 2)
{
double val = Amplitude * Math.Sin(sinMult * time);
short sval = (short)(Math.Round(val * (short.MaxValue - 1)));
buffer[offset + i * 2] = (byte)(sval & 0xFF);
buffer[offset + i * 2 + 1] = (byte)((sval >> 8) & 0xFF);
}
return rc * 2;
}
}
類似或者是你的代碼?你有沒有搜索谷歌,或只是問問題? – wudzik
@wudzik與我的代碼類似,當然是的,我做過了嗎?現在你能幫助我嗎?還是會回答問題?任何方式謝謝,爲節省時間。 –
那麼你爲什麼不粘貼你的實際代碼?對不起浪費你寶貴的時間,但問好問題可以節省很多時間。 http://stackoverflow.com/questions/5485577/c-sharp-naudio-playing-sine-wave-for-x-milliseconds?rq=1在這裏你看到你不能把時間傳遞給naudio – wudzik