11
15

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.

numpy の配列を wave モジュールを使って wav ファイルに保存

Posted at

何をしたいか

numpy で保持されている音の波形データを、ファイルに保存したい。
ただし、scikits.audiolab ではなくて、標準のモジュールだけを使ってしたい。

詰まったところと解決策

Wave_write クラスのパラメータ

Wave_write クラスのドキュメント
setparams で渡すパラメータのうち4番目のフレーム数は、
「あとからフレームが書き込まれるとフレーム数は変更されます。」
と書かれているが、0 にするとうまく行かなかった。

バイナリの作り方

wave の writeframes に渡す波形を表すバイナリの作り方。
numpy.tostring() だとダメで、 array で 'h' に変換したあと、tostring するとうまくできた。

コード

import numpy, wave, array
filename = "wave_file_name.wav"

# save wav file
buf = <numpy の波形データが入っている>
w = wave.Wave_write(filename)
w.setparams((
    1,                        # channel
    2,                        # byte width
    16000,                    # sampling rate
    len(buf),                 # number of frames
    "NONE", "not compressed"  # no compression
))
w.writeframes(array.array('h', buf).tostring())
w.close()
11
15
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
11
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?