-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbeep.go
More file actions
66 lines (58 loc) · 1.34 KB
/
beep.go
File metadata and controls
66 lines (58 loc) · 1.34 KB
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
package beepster
import (
"os"
"syscall"
"time"
)
const (
KIOCSOUND = 0x4B2F
CLOCK_TICK_RATE = 1193180
)
type Note struct {
Freq float32 // Frequency (Hz)
Length uint32 // Length of note (ms)
Delay uint32 // Delay after note (ms)
}
type Speaker struct {
// File for speaker access
file *os.File
}
// Create a new speaker object ready for use
func Open() *Speaker {
// Open speaker
fd, err := os.Create("/dev/tty0")
if err != nil {
panic(err)
}
speaker := new(Speaker)
speaker.file = fd
return speaker
}
// Makes the speaker play a certain tone.
// To stop it, call it with a frequency of 0
func (spkr *Speaker) Beep(freq float32) {
if freq != 0 {
// Beep at the given pitch
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, spkr.file.Fd(), uintptr(KIOCSOUND), uintptr(CLOCK_TICK_RATE/freq))
} else {
// Cease the beeping
_, _, _ = syscall.Syscall(syscall.SYS_IOCTL, spkr.file.Fd(), uintptr(KIOCSOUND), uintptr(0))
}
}
// Plays an entire Note object
func (spkr *Speaker) PlayNote(note *Note) {
spkr.Beep(note.Freq)
time.Sleep(time.Duration(note.Length) * time.Millisecond)
spkr.Beep(0)
time.Sleep(time.Duration(note.Delay) * time.Millisecond)
}
// Properly shutdowns the speaker
func (spkr *Speaker) Close() {
// Stop all beeping
spkr.Beep(0)
// Close the speaker
err := spkr.file.Close()
if err != nil {
panic(err)
}
}