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,31 +463,36 @@ 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 {
buf := make([]byte, 4096) t = time.After(10 * time.Millisecond)
n, err := p.src.Read(buf) p.m.Unlock()
p.buf = append(p.buf, buf[:n]...) break
if err == io.EOF {
p.srcEOF = true
}
if p.srcEOF && len(p.buf) == 0 {
p.m.Unlock()
return
}
if err != nil && err != io.EOF {
p.readErr = err
p.m.Unlock()
return
}
} }
buf := make([]byte, 4096)
n, err := p.src.Read(buf)
p.buf = append(p.buf, buf[:n]...)
if err == io.EOF {
p.srcEOF = true
}
if p.srcEOF && len(p.buf) == 0 {
t = nil
p.m.Unlock()
return
}
if err != nil && err != io.EOF {
p.readErr = err
t = nil
p.m.Unlock()
return
}
t = time.After(time.Millisecond)
p.m.Unlock() p.m.Unlock()
} }
} }