如何在 C# 中使用 NAudio(或其他方式)播放音符?

问题描述 投票:0回答:1

我为 Winforms 开发了 NAudio。有人有如何使用 NAudio (或通过其他方式)演奏音符的示例吗?我希望这会是类似于以下的简单内容:

NAudio.PlayNote(28, 100); // 28 == 41.203 == Open E String on a bass

...第一个参数是音符的 Midi 编号,第二个参数是播放该音符的毫秒数。

但我意识到事情可能没那么简单;有人能指出我正确的方向吗?

更新

当我尝试使用 NAudio.Midi 时,如下所示,我在 using 子句中得到了这个:

...当尝试在代码中调用该方法时:

c# winforms naudio
1个回答
0
投票

我不认为NAudio有像

NAudio.PlayNote
那样的直接方法。

NAudio 支持 MIDI 功能,包括发送 MIDI 事件。这意味着,要播放 MIDI 音符,您通常会发送

NoteOnEvent
到 MIDI 输出设备,然后发送
NoteOffEvent
来停止音符。确保您已将 NAudio NuGet 包正确添加到项目中,并具有正确的
using
指令。
naudio/NAudio
第183期
提到了错误“
The type or namespace Midi does not exist in namespace NAudio
”,但仅适用于UWP(通用Windows平台)

using NAudio.Midi;
using NAudio.Wave;

using (var midiOut = new MidiOut(0)) // 0 is the device number, adjust as needed
{
    // Send a NoteOn event to start the note
    var noteOn = new NoteOnEvent(0, 1, 28, 100, 0); // channel 1, note 28, velocity 100, at time 0
    midiOut.Send(noteOn.GetAsShortMessage());
    
    // Wait for the duration of the note
    System.Threading.Thread.Sleep(1000); // 1000ms = 1 second
    
    // Send a NoteOff event to stop the note
    var noteOff = new NoteOffEvent(0, 1, 28, 100, 0); // channel 1, note 28, velocity 100, at time 0
    midiOut.Send(noteOff.GetAsShortMessage());
}

注意;在 issue 569 之后,您的

NoteOffEvent
必须具有速度。

如果您喜欢为每个音符使用 WAV 文件,则需要为要播放的每个音符提供 WAV 文件:

using NAudio.Wave;

using (var outputDevice = new WaveOutEvent())
{
    // Load the WAV file for the note you want to play
    using (var audioFile = new AudioFileReader(@"path_to_your_note_file.wav"))
    {
        // Initialize the output device with the audio file
        outputDevice.Init(audioFile);
        
        // Play the audio
        outputDevice.Play();
        
        // Wait for the audio to finish playing
        while (outputDevice.PlaybackState == PlaybackState.Playing)
        {
            System.Threading.Thread.Sleep(100);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.