Sử dụng NAudio thư viện cho đầu ra âm thanh.
Hãy ghi chú cung cấp sóng:
class NotesWaveProvider : WaveProvider32
{
public NotesWaveProvider(Queue<Note> notes)
{
this.Notes = notes;
}
public readonly Queue<Note> Notes;
int sample = 0;
Note NextNote()
{
for (; ;)
{
if (Notes.Count == 0)
return null;
var note = Notes.Peek();
if (sample < note.Duration.TotalSeconds * WaveFormat.SampleRate)
return note;
Notes.Dequeue();
sample = 0;
}
}
public override int Read(float[] buffer, int offset, int sampleCount)
{
int sampleRate = WaveFormat.SampleRate;
for (int n = 0; n < sampleCount; n++)
{
var note = NextNote();
if (note == null)
buffer[n + offset] = 0;
else
buffer[n + offset] = (float)(note.Amplitude * Math.Sin((2 * Math.PI * sample * note.Frequency)/sampleRate));
sample++;
}
return sampleCount;
}
}
class Note
{
public float Frequency;
public float Amplitude = 1.0f;
public TimeSpan Duration = TimeSpan.FromMilliseconds(50);
}
bắt đầu chơi:
WaveOut waveOut;
this.Notes = new Queue<Note>(new[] { new Note { Frequency = 1000 }, new Note { Frequency = 1100 } });
var waveProvider = new NotesWaveProvider(Notes);
waveProvider.SetWaveFormat(16000, 1); // 16kHz mono
waveOut = new WaveOut();
waveOut.Init(waveProvider);
waveOut.Play();
thêm ghi chú mới:
void Timer_Tick(...)
{
if (Notes.Count < 10)
Notes.Add(new Note{Frecuency = 900});
}
ps mã này chỉ là ý tưởng. cho thực tế sử dụng thêm mt-khóa vv
Nguồn
2012-03-07 14:47:19
Hoạt động rất tốt đẹp để khởi động một chuỗi các ghi chú. , thêm nhiều ghi chú vào hàng đợi sau khi "giai điệu" ban đầu đã hoàn thành không hoạt động đúng cách. Bạn có thể nhận được ghi chú mới để bắt đầu ngay lập tức. Notes.Count == 0) trả về null;, .. mã của tôi bây giờ là: if (Notes.Count == 0) {sample = 0; return null;}. Trong trường hợp này, ghi chú tiếp theo sẽ bắt đầu ngay lập tức, nếu nó được đưa ra một vài giây sau đó, vì vậy, (for;;) là không cần thiết trong NextNote. – Goodies