Skip to content

Commit

Permalink
Player initialized on Play() call
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexEidt committed Sep 28, 2022
1 parent ebb98d4 commit f946c8a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
2 changes: 1 addition & 1 deletion audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ func (audio *Audio) Read() bool {
return false
}

// If cmd is nil, video reading has not been initialized.
// If cmd is nil, audio reading has not been initialized.
if audio.cmd == nil {
if err := audio.init(); err != nil {
return false
Expand Down
40 changes: 25 additions & 15 deletions player.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,37 +45,40 @@ func NewPlayer(channels, samplerate int, format string) (*Player, error) {
return nil, err
}

player := &Player{
samplerate: samplerate,
channels: channels,
format: format,
}

return player, nil
}

func (player *Player) init() error {
player.cleanup()

cmd := exec.Command(
"ffplay",
"-f", format,
"-ac", fmt.Sprintf("%d", channels),
"-ar", fmt.Sprintf("%d", samplerate),
"-f", player.format,
"-ac", fmt.Sprintf("%d", player.channels),
"-ar", fmt.Sprintf("%d", player.samplerate),
"-i", "-",
"-nodisp",
"-autoexit",
"-loglevel", "quiet",
)

player := &Player{
samplerate: samplerate,
channels: channels,
format: format,
cmd: cmd,
}

pipe, err := cmd.StdinPipe()
if err != nil {
return nil, err
return err
}
player.pipe = &pipe

if err := cmd.Start(); err != nil {
return nil, err
return err
}

player.cleanup()

return player, nil
return nil
}

func (player *Player) Play(samples interface{}) error {
Expand All @@ -84,6 +87,13 @@ func (player *Player) Play(samples interface{}) error {
return fmt.Errorf("invalid sample data type")
}

// If cmd is nil, audio player has not been initialized.
if player.cmd == nil {
if err := player.init(); err != nil {
return err
}
}

total := 0
for total < len(buffer) {
n, err := (*player.pipe).Write(buffer[total:])
Expand Down

0 comments on commit f946c8a

Please sign in to comment.