0
0

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 3 years have passed since last update.

pythonで数値テキストからwavファイル生成

Posted at

1. はじめに

テキスト出力した44kSa/s 音声データをwavファイルにするpythonスクリプトです.

2. 概要

numpyとwaveモジュールを使います.
テキストの数値データをnumpyのloadtxtで読み込み,waveのWave_writeでファイル出力します.
途中,DCオフセット除去や正規化とクリッピング処理をし,符号付き16bit整数にしています.

3. スクリプト

正規化は最大値で行っています.RMSで行った方が音量は大きくなりますが,クリッピングで歪むのを避けるためです.実行時に引数を使っているのでimport sysしています.

txt2wav44k.py
import wave
import numpy as np
import sys

#usage:
#python3 txt2wav44k.py dat01.txt

aryArg = sys.argv
if len(aryArg) > 1:
	fnamel = aryArg[1]
else:
	fnamel ='dat00.txt'

fnames= fnamel[0:-3]+'wav'
fs=44100

strmOrg=np.loadtxt(fnamel)
N=len(strmOrg)
timlen=N/fs #sec

factScl = 0.90
strmOrg = strmOrg - np.mean(strmOrg)
myRms = np.sqrt(np.mean(strmOrg*strmOrg))
myMax = np.max(np.abs(strmOrg))


#streamNrm = strmOrg / myRms * factScl
streamNrm = strmOrg / myMax * factScl

streamPeakSup = np.where( streamNrm < 1.0 , streamNrm , 1.0)
streamPeakSup = np.where( streamPeakSup > -1.0 , streamPeakSup , -1.0)
streamOut = streamPeakSup

scaleFixedPoint = 32767
stream= np.int16(streamOut * scaleFixedPoint)

objw = wave.Wave_write(fnames)
objw.setnchannels(1)
objw.setsampwidth(2)
objw.setframerate(fs)
objw.writeframes(stream)
objw.close()

#from playsound import playsound
#playsound(fnames)

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?