audio: Change init from a variable to a channel

This commit is contained in:
Hajime Hoshi 2019-05-02 02:23:41 +09:00
parent bea5b0f685
commit 5121b072f1

View File

@ -55,9 +55,13 @@ const (
type Context struct { type Context struct {
c context c context
// inited represents whether the audio device is initialized and available or not.
// On Android, audio loop cannot be started unless JVM is accessible. After updating one frame, JVM should exist.
inited chan struct{}
initedOnce sync.Once
sampleRate int sampleRate int
err error err error
inited bool
suspended bool suspended bool
ready bool ready bool
@ -94,6 +98,7 @@ func NewContext(sampleRate int) (*Context, error) {
sampleRate: sampleRate, sampleRate: sampleRate,
c: newContext(sampleRate), c: newContext(sampleRate),
players: map[*playerImpl]struct{}{}, players: map[*playerImpl]struct{}{},
inited: make(chan struct{}),
} }
theContext = c theContext = c
@ -110,10 +115,9 @@ func NewContext(sampleRate int) (*Context, error) {
}) })
h.AppendHookOnBeforeUpdate(func() error { h.AppendHookOnBeforeUpdate(func() error {
// On Android, audio loop cannot be started unless JVM is accessible. After updating one frame, JVM should exist. c.initedOnce.Do(func() {
c.m.Lock() close(c.inited)
c.inited = true })
c.m.Unlock()
var err error var err error
theContextLock.Lock() theContextLock.Lock()
@ -139,10 +143,9 @@ func CurrentContext() *Context {
func (c *Context) playable() bool { func (c *Context) playable() bool {
c.m.Lock() c.m.Lock()
i := c.inited
s := c.suspended s := c.suspended
c.m.Unlock() c.m.Unlock()
return i && !s return !s
} }
func (c *Context) hasError() bool { func (c *Context) hasError() bool {
@ -393,6 +396,8 @@ func (p *playerImpl) Play() {
} }
func (p *playerImpl) loop() { func (p *playerImpl) loop() {
<-p.context.inited
w := p.context.c.NewPlayer() w := p.context.c.NewPlayer()
wclosed := make(chan struct{}) wclosed := make(chan struct{})
defer func() { defer func() {