Class: Discorb::Voice::FFmpegAudio

Inherits:
Object
  • Object
show all
Defined in:
lib/discorb/voice/source.rb

Overview

Note:

You must install FFmpeg and should be on the PATH.

Plays audio from a source, using FFmpeg.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, bitrate: 128, extra_options: {}, extra_options2: {}) ⇒ FFmpegAudio

Creates a new FFmpegAudio.

Parameters:

  • source (String, IO)

    The source of audio data.

  • bitrate (Integer) (defaults to: 128)

    The bitrate of the audio.

  • extra_options ({String => String}) (defaults to: {})

    Extra options for FFmpeg. This will be passed before ‘-i`.

  • extra_options2 ({String => String}) (defaults to: {})

    Extra options for FFmpeg. This will be passed after ‘-i`.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/discorb/voice/source.rb', line 45

def initialize(source, bitrate: 128, extra_options: {}, extra_options2: {})
  if source.is_a?(String)
    source_path = source
    @tmp_path = nil
  else
    source_path = "#{Dir.tmpdir}/#{Process.pid}.#{source.object_id}"
    @tmp_path = source_path
    File.open(source_path, "wb") do |f|
      while chunk = source.read(4096)
        f.write(chunk)
      end
    end
  end
  args = %w[ffmpeg]
  extra_options.each do |key, value|
    args += ["-#{key}", "#{value}"]
  end
  args += %W[
    -i #{source_path}
    -f opus
    -c:a libopus
    -ar 48000
    -ac 2
    -b:a #{bitrate}k
    -loglevel warning
    -map_metadata -1]
  extra_options2.each do |key, value|
    args += ["-#{key}", "#{value}"]
  end
  args += %w[pipe:1]
  @stdin, @stdout, @process = Open3.popen2(*args)
end

Instance Attribute Details

#processObject (readonly)

Returns the value of attribute process.



35
36
37
# File 'lib/discorb/voice/source.rb', line 35

def process
  @process
end

#stderrObject (readonly)

Returns the value of attribute stderr.



35
36
37
# File 'lib/discorb/voice/source.rb', line 35

def stderr
  @stderr
end

#stdinObject (readonly)

Returns the value of attribute stdin.



35
36
37
# File 'lib/discorb/voice/source.rb', line 35

def stdin
  @stdin
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



35
36
37
# File 'lib/discorb/voice/source.rb', line 35

def stdout
  @stdout
end

Instance Method Details

#cleanupObject

Kills the FFmpeg process, and closes io.



85
86
87
88
89
90
# File 'lib/discorb/voice/source.rb', line 85

def cleanup
  @process.kill
  @stdin.close
  @stdout.close
  File.delete(@tmp_path) if @tmp_path
end

#ioObject



78
79
80
# File 'lib/discorb/voice/source.rb', line 78

def io
  @stdout
end