audio: Discard audio data when queue seems full

This commit is contained in:
Hajime Hoshi 2017-07-09 05:06:34 +09:00
parent 5cf7b2491a
commit 2552f1625d

View File

@ -177,6 +177,7 @@ type Context struct {
sampleRate int sampleRate int
frames int64 frames int64
writtenBytes int64 writtenBytes int64
unwrittenCount int
} }
var ( var (
@ -223,8 +224,7 @@ func (c *Context) Update() error {
// e.g. a variable for JVM on Android might not be set. // e.g. a variable for JVM on Android might not be set.
if c.playerWriteCh == nil { if c.playerWriteCh == nil {
init := make(chan error) init := make(chan error)
// 4 is (buffer size) / (bytes for 1 frame). c.playerWriteCh = make(chan []uint8)
c.playerWriteCh = make(chan []uint8, 4)
c.playerErrCh = make(chan error, 1) c.playerErrCh = make(chan error, 1)
c.playerCloseCh = make(chan struct{}) c.playerCloseCh = make(chan struct{})
go func() { go func() {
@ -269,10 +269,18 @@ func (c *Context) Update() error {
close(c.playerCloseCh) close(c.playerCloseCh)
return err return err
} }
// Discard when the buffer queue seems full.
if c.unwrittenCount > 0 {
c.unwrittenCount--
return nil
}
select { select {
case c.playerWriteCh <- buf: case c.playerWriteCh <- buf:
// Writing can block. Don't wait for the result here. // Writing can block. Don't wait for the result here.
default: default:
// The current buffer size is 1/15 [sec] = 4 [frames].
// Wait for 5 [frames] which is more than 4.
c.unwrittenCount = 5
} }
return nil return nil
} }