timerをdatetimeクラスで測定してみたらばらつきが大きかったけど、音を断続させてみたらどうなるか確かめてみた。
NAudioを使ってサイン波を発生させ、音量をコントロールして断続させてみた。 ちなみにNAudioによるサイン波の発生は、このサイトのソースをそのままいただいた。
NuGetからNAudio.coreとNAudio.WinFormsをインストールしておく。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
using NAudio.Wave; using System; using System.Windows.Forms; namespace SW_generator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public abstract class WaveProvider32 : IWaveProvider { private WaveFormat waveFormat; public WaveProvider32() : this(44100, 1) { } public WaveProvider32(int sampleRate, int channels) { SetWaveFormat(sampleRate, channels); } public void SetWaveFormat(int sampleRate, int channels) { this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels); } public int Read(byte[] buffer, int offset, int count) { WaveBuffer waveBuffer = new WaveBuffer(buffer); int samplesRequired = count / 4; int samplesRead = Read(waveBuffer.FloatBuffer, offset / 4, samplesRequired); return samplesRead * 4; } public abstract int Read(float[] buffer, int offset, int sampleCount); public WaveFormat WaveFormat { get { return waveFormat; } } } public class SineWaveProvider32 : WaveProvider32 { int sample; public SineWaveProvider32() { Frequency = 1000; Amplitude = 0.25f; // let's not hurt our ears } public float Frequency { get; set; } public float Amplitude { get; set; } public override int Read(float[] buffer, int offset, int sampleCount) { int sampleRate = WaveFormat.SampleRate; for (int n = 0; n < sampleCount; n++) { buffer[n + offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate)); sample++; if (sample >= sampleRate) sample = 0; } return sampleCount; } } private WaveOut waveOut; private void StartStopSineWave() { if (waveOut == null) { var sineWaveProvider = new SineWaveProvider32(); sineWaveProvider.Frequency = 800; sineWaveProvider.Amplitude = 0.5f; waveOut = new WaveOut(); waveOut.Init(sineWaveProvider); waveOut.Play(); timer1.Start(); } else { waveOut.Stop(); waveOut.Dispose(); waveOut = null; timer1.Stop(); } } private void button1_Click(object sender, EventArgs e) { StartStopSineWave(); } private void button2_Click(object sender, EventArgs e) { waveOut.Volume = 0.0f; } bool onoff = false; private void timer1_Tick(object sender, EventArgs e) { if (onoff) { waveOut.Volume = 0.0f; onoff = false; } else { waveOut.Volume = 0.5f; onoff = true; } } } } |
音の断続はインターバルが38msだと少し違和感があるけど、50ms程度にするとそれほど違和感はない。