audio: Refactoring

This commit is contained in:
Hajime Hoshi 2017-12-23 17:05:14 +09:00
parent 3dcb486a5c
commit ba3de063ac

View File

@ -446,15 +446,16 @@ func (p *Player) Play() error {
func (p *Player) startRead() { func (p *Player) startRead() {
p.m.Lock() p.m.Lock()
if !p.reading && p.readErr == nil { if !p.reading && p.readErr == nil {
p.reading = true
p.closeCh = make(chan struct{}) p.closeCh = make(chan struct{})
p.closedCh = make(chan struct{}) p.closedCh = make(chan struct{})
p.reading = true
p.srcEOF = false p.srcEOF = false
go func() { go func() {
p.readLoop() p.readLoop()
p.m.Lock() p.m.Lock()
p.reading = false p.reading = false
p.m.Unlock() p.m.Unlock()
// TODO: How about rewinding?
close(p.closedCh) close(p.closedCh)
}() }()
} }
@ -462,15 +463,18 @@ func (p *Player) startRead() {
} }
func (p *Player) readLoop() { func (p *Player) readLoop() {
t := time.Tick(time.Millisecond) t := time.After(0)
for { for {
select { select {
case <-p.closeCh: case <-p.closeCh:
p.closeCh = nil
return return
case <-t: case <-t:
p.m.Lock() p.m.Lock()
if len(p.buf) < 4096*16 && !p.srcEOF { if len(p.buf) >= 4096*16 {
t = time.After(10 * time.Millisecond)
p.m.Unlock()
break
}
buf := make([]byte, 4096) buf := make([]byte, 4096)
n, err := p.src.Read(buf) n, err := p.src.Read(buf)
p.buf = append(p.buf, buf[:n]...) p.buf = append(p.buf, buf[:n]...)
@ -478,15 +482,17 @@ func (p *Player) readLoop() {
p.srcEOF = true p.srcEOF = true
} }
if p.srcEOF && len(p.buf) == 0 { if p.srcEOF && len(p.buf) == 0 {
t = nil
p.m.Unlock() p.m.Unlock()
return return
} }
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
p.readErr = err p.readErr = err
t = nil
p.m.Unlock() p.m.Unlock()
return return
} }
} t = time.After(time.Millisecond)
p.m.Unlock() p.m.Unlock()
} }
} }