This repository has been archived by the owner on Jul 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice_winmm.go
125 lines (108 loc) · 2.35 KB
/
device_winmm.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// +build windows
package gosound
import (
"context"
"errors"
"time"
"github.com/gotracker/gomixing/mixing"
winmm "github.com/heucuva/go-winmm"
)
const winmmName = "winmm"
type winmmDevice struct {
device
mix mixing.Mixer
waveout *winmm.WaveOut
}
func (d *winmmDevice) GetKind() Kind {
return KindSoundCard
}
func newWinMMDevice(settings Settings) (Device, error) {
d := winmmDevice{
device: device{
onRowOutput: settings.OnRowOutput,
},
mix: mixing.Mixer{
Channels: settings.Channels,
BitsPerSample: settings.BitsPerSample,
},
}
var err error
d.waveout, err = winmm.New(settings.Channels, settings.SamplesPerSecond, settings.BitsPerSample)
if err != nil {
return nil, err
}
if d.waveout == nil {
return nil, errors.New("could not create winmm device")
}
return &d, nil
}
// Name returns the device name
func (d *winmmDevice) Name() string {
return winmmName
}
// Play starts the wave output device playing
func (d *winmmDevice) Play(in <-chan *PremixData) error {
return d.PlayWithCtx(context.Background(), in)
}
// PlayWithCtx starts the wave output device playing
func (d *winmmDevice) PlayWithCtx(ctx context.Context, in <-chan *PremixData) error {
type RowWave struct {
Wave *winmm.WaveOutData
Row *PremixData
}
panmixer := mixing.GetPanMixer(d.mix.Channels)
if panmixer == nil {
return errors.New("invalid pan mixer - check channel count")
}
myCtx, cancel := context.WithCancel(ctx)
out := make(chan RowWave, 3)
go func() {
defer cancel()
defer close(out)
for {
select {
case <-myCtx.Done():
return
case row, ok := <-in:
if !ok {
return
}
mixedData := d.mix.Flatten(panmixer, row.SamplesLen, row.Data, row.MixerVolume)
rowWave := RowWave{
Wave: d.waveout.Write(mixedData),
Row: row,
}
out <- rowWave
}
}
}()
for {
select {
case <-myCtx.Done():
return myCtx.Err()
case rowWave, ok := <-out:
if !ok {
// done!
return nil
}
if d.onRowOutput != nil {
d.onRowOutput(KindSoundCard, rowWave.Row)
}
for !d.waveout.IsHeaderFinished(rowWave.Wave) {
time.Sleep(time.Microsecond * 1)
}
}
}
}
// Close closes the wave output device
func (d *winmmDevice) Close() {
if d.waveout != nil {
d.waveout.Close()
}
}
func init() {
Map[winmmName] = deviceDetails{
create: newWinMMDevice,
Kind: KindSoundCard,
}
}