30
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】Carrierwave で音声ファイルをアップロード&変換する

Last updated at Posted at 2017-07-18

Railsの画像アップロードライブラリとして有名な carrierwave は,音声ファイルでもアップロードできる.

設定方法は画像と同じ

Gemfile
gem 'carrierwave'

アップローダーを生成.

$ bundle exec rails g uploader AudioFile

file カラムにアップローダーを適用.

app/models/audio.rb
class Audio < ApplicationRecord
  mount_uploader :file, AudioFileUploader

  validates :title, presence: true
  validates :file, presence: true
end

ファイル形式を変換 (.mp3)

.mp3 に変換したい場合は,carrierwave-audio が使える.

app/uploader/audio_file_uploader.rb
class AudioFileUploader < CarrierWave::Uploader::Base
  # 追記
  include CarrierWave::Audio

  # 追記
  version :mp3 do
    process :convert => [{output_format: :mp3}]

    def full_filename(for_file)
      "#{super.chomp(File.extname(super))}.mp3"
    end
  end
end
audio = Audio.find(1)
audio.file.mp3.url # /uploads/audio/file/1/sample1.mp3

ファイル形式を変換 (.wav)

上記ライブラリは .mp3 のみ対応だったので,forkで.wav変換を実装した.

Gemfile
gem 'carrierwave-audio', git: 'git@github.com:tanakaworld/carrierwave-audio.git'
app/uploader/audio_file_uploader.rb
class AudioFileUploader < CarrierWave::Uploader::Base
  # 追記
  version :wav do
   process :convert => [{output_format: :wav}]

   def full_filename(for_file)
     "#{super.chomp(File.extname(super))}.wav"
   end
 end
end
audio = Audio.find(1)
audio.file.wav.url # /uploads/audio/file/1/sample1.wav
30
34
0

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
  3. You can use dark theme
What you can do with signing up
30
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?