18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#で再生デバイスを指定してサウンドを再生

Posted at

NAudioを使用しますので、Nuget等を使ってプロジェクトに組み込んでください。

再生デバイスの取得

以下の感じでさくっと取得。
capabilitiesの中にはGuidやらいろいろ入っていますが、今回は特に使わないです。結局あとで必要になるのは「再生デバイスのindex」だけっぽいので、とりあえず名前だけ返却しましょう。

public List<string> GetDevices()
{
    List<string> deviceList = new List<string>();
    for (int i = 0; i < WaveOut.DeviceCount; i++)
    {
        var capabilities = WaveOut.GetCapabilities(i);
        deviceList.Add(capabilities.ProductName);
    }
    return deviceList;
}

デバイスを指定して再生

NAudio(というかWaveOut)の仕様では、indexを指定することでデバイスを特定するようです。

public void PlaySound(string filePath, int index)
{
    var waveReader = new NAudio.Wave.WaveFileReader(filePath);
    var waveOut = new NAudio.Wave.WaveOut();
    waveOut.DeviceNumber = index;
    waveOut.Init(waveReader);
    waveOut.Play();
}

その他

普段はヘッドホンで音を出している私が、特定のタイミングでモニターから音を出したいケースが発生したので調べてみたところ、思いのほかはまったのでメモしときました。

最初はXAudio2を使って再生しようと思い、SharpDXやSlimDXを試していたのですが、XAudio2のバージョン2.8以降はデバイスの特定に「デバイスインターフェースID」的なものが必要になるようです。
しかしローレベルAPIが理解できないライトちゃんには、再生デバイスのインターフェースIDなんてわかりまてん。とっとと諦めてこちらの方法に切り替えました。

あんまり無い要件かと思いますが、誰かの助けになれば・・・

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?