search
LoginSignup
1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

Rubyで音(wav)を書き出してみた

小ネタです。
Rubyで音声ファイルって作れないのかなと思ったら、こんな感じでやるとできそうです。

gem install numo-narray
gem install wavefile

サイン波っぽいの

require "wavefile"
require "numo/narray"

include WaveFile

frequency = 440.0    # 生成するサイン波の周波数
seconds   = 1.0      # 生成する音の秒数
rate      = 44100    # 出力するwavファイルのサンプリング周波数

a = Numo::SFloat.linspace(0, 2 * Math::PI * frequency, rate) # 本当はrate+1として1個削るべき?
b = Numo::NMath.sin(a)
wave = b.to_a

buffer = Buffer.new(b.to_a, Format.new(:mono, :float, rate))

Writer.new("sin.wav", Format.new(:mono, :pcm_16, rate)) do |writer|
  writer.write(buffer)
end

三角波はこんな感じかな?

require "wavefile"
include WaveFile
rate      = 44100

triangle = Array.new(100){|i|
  i < 50 ? i : 100 - i
}.map{|i| i / 50.0 - 0.5}

buffer = Buffer.new(triangle, Format.new(:mono, :float, rate))

Writer.new("triangle.wav", Format.new(:mono, :pcm_16, rate)) do |writer|
  441.times{writer.write(buffer)}
end

矩形波はこんな感じ?

require "wavefile"

include WaveFile

rate      = 44100
kukei = Array.new(50, -0.5).concat(Array.new(50, 0.5))

buffer = Buffer.new(kukei, Format.new(:mono, :float, rate))

Writer.new("kukei.wav", Format.new(:mono, :pcm_16, rate)) do |writer|
  441.times{writer.write(buffer)}
end

FlammarionでGUI化してみると面白そうだ。

参考資料

Python で音楽を作って楽しもう

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1
Help us understand the problem. What are the problem?