ロゴ メインコンテンツへ
RSSフィード
「ソフトウェア開発」に関連する記事一覧

C# NAudioでwavファイルをループ再生する

2021/08/01
(この記事の文字数: 225)

C#でNAudioを使って .wav ファイルを再生する時にループ再生ってどうやるのかなと思い、調べた内容をメモしておきます。

結論としては、以下のページにチュートリアルがあって、こちらに書いてあるクラスをコピペして使用したらループ再生できました。

https://www.markheath.net/post/looped-playback-in-net-with-naudio

こちらの記事にもクラスのコードを貼っておきます。

public class LoopStream : WaveStream
{
    WaveStream sourceStream;

    public LoopStream(WaveStream sourceStream)
    {
        this.sourceStream = sourceStream;
        this.EnableLooping = true;
    }

    public bool EnableLooping { get; set; }

    public override WaveFormat WaveFormat
    {
        get { return sourceStream.WaveFormat; }
    }

    public override long Length
    {
        get { return sourceStream.Length; }
    }

    public override long Position
    {
        get { return sourceStream.Position; }
        set { sourceStream.Position = value; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        int totalBytesRead = 0;

        while (totalBytesRead < count)
        {
            int bytesRead = sourceStream.Read(buffer, offset + totalBytesRead, count - totalBytesRead);
            if (bytesRead == 0)
            {
                if (sourceStream.Position == 0 || !EnableLooping)
                {
                    // something wrong with the source stream
                    break;
                }
                // loop
                sourceStream.Position = 0;
            }
            totalBytesRead += bytesRead;
        }
        return totalBytesRead;
    }
}

このクラスの使い方は以下です。

WaveFileReader reader = new WaveFileReader(@"C:\Music\Example.wav");
LoopStream loop = new LoopStream(reader);
waveOut = new WaveOut();
waveOut.Init(loop);
waveOut.Play();

  このエントリーをはてなブックマークに追加  

<<「ソフトウェア開発」の記事一覧に戻る

<<「ソフトウェア開発」の次の記事
「ソフトウェア開発」の前の記事 >>

コメント(0 件)



コンテンツロード: 0.0084 sec
Copyright(C)2006-2024 puarts All Rights Reserved