音频库的信号发生器类 - 持续时间播放

本文关键字:持续时间 播放 信号发生器 音频 | 更新日期: 2023-09-27 17:56:21

>我使用 naudio 生成指定频率的音调,如下所示:

private void gen_Sinus(double frequency)
    {
        WaveOut _myWaveOut = new WaveOut();
        SignalGenerator mySinus = new SignalGenerator(44100, 1);//using NAudio.Wave.SampleProviders; 
        mySinus.Frequency = frequency;
        mySinus.Type = SignalGeneratorType.Sin;
        _myWaveOut.Init(mySinus);
        _myWaveOut.Play();
    }

我希望在单击按钮时,它将在特定时间内播放该音调,该音调将传递给此方法。让我们以它为例:

double toneDuration

我宁愿阻止一些睡眠方法,因为它必须尽可能准确。

音频库的信号发生器类 - 持续时间播放

您可以使用

OffsetSampleProvider来执行此操作,并设置Take持续时间:

var trimmed = new OffsetSampleProvider(signalGenerator);
trimmed.Take = TimeSpan.FromSeconds(10);
waveOut.Init(trimmed);
waveOut.Play();

使用计时器和等待处理程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Tick += new EventHandler(timer1_Tick);
        }
        static AutoResetEvent autoEvent = new AutoResetEvent(false);
        private void gen_Sinus(double frequency)
        {
            WaveOut _myWaveOut = new WaveOut();
            SignalGenerator mySinus = new SignalGenerator(44100, 1);//using NAudio.Wave.SampleProviders; 
            mySinus.Frequency = frequency;
            mySinus.Type = SignalGeneratorType.Sin;
            _myWaveOut.Init(mySinus);
            timer1.Interval = 5000;
            timer1.Start()
            _myWaveOut.Play();
            autoEvent.Reset();
            autoEvent.WaitOne();
            _myWaveOut.Stop();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            autoEvent.Set();
        }
    }
}
​