본문 바로가기
개발언어/NAudio

[NAudio] 반복재생하기

by 창용이랑 2021. 7. 8.
728x90

이번에도 역시 예제를 기반으로 약간 수정했다.

 

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

Looped Playback in .NET with NAudio

Mark Heath's Development Blog

markheath.net

 

 

위 예제는 음원이 종료되면 다시 시작하는 방식이라서, 원하는 위치를 지정하고 해당 위치에서 반복할 수 있도록 했다.

매우 단순하니 그냥 코드만 적어놓겠다.

 

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
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace SoundWingTest
{
    public class LoopStream : WaveStream
    {
        WaveStream sourceStream;
        
        //반복재생 클래스. 기본값은 loop 하지 않음.
        public LoopStream(WaveStream sourceStream)
        {
            this.sourceStream = sourceStream;
            this.EnableLooping = false;
            startLoop = new TimeSpan(0);
            endLoop = sourceStream.TotalTime;
            //sourceStream.CurrentTime
        }
        
        public bool EnableLooping { get; set; }


        //반복재생 시작/종료 위치
        public TimeSpan startLoop { get; set; }
        public TimeSpan endLoop { 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);
                // loop
                if (EnableLooping && sourceStream.CurrentTime >= endLoop)
                {
                    Debug.WriteLine("time : " + sourceStream.CurrentTime.ToString());
                    sourceStream.CurrentTime = startLoop;
                    break;
                }
                if (bytesRead == 0)
                {
                    if (sourceStream.Position == 0 || !EnableLooping)
                    {
                        break;
                    }
                }
                totalBytesRead += bytesRead;
            }
            return totalBytesRead;
        }
    }
}


Colored by Color Scripter
cs

 

출처 : https://m.blog.naver.com/luku756/221954647158

'개발언어 > NAudio' 카테고리의 다른 글

[Digital Audio] 2. Audio File Format  (0) 2021.07.08
[Digital Audio] 1. Audio Sampling  (0) 2021.07.08
[NAudio] 재생 속도 조절  (0) 2021.07.08
[NAudio] Spectrogram 그리기  (0) 2021.07.08
[NAudio] 6. Recording Audio  (0) 2021.07.08