0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで読み込んだ音声ファイルを指定した周波数以上の音ををカットするプログラム(ローパスフィルター)

Posted at

まずpyhubをインストールします。

install.py
pip install pydub scipy

次にプログラムです。

program.py
from pydub import AudioSegment
import numpy as np
from scipy.signal import butter, lfilter
from google.colab import files

# 音源をアップロードする
uploaded = files.upload()

# アップロードされたファイル名を取得
input_file = list(uploaded.keys())[0]
print(f"Uploaded file: {input_file}")

# カットオフ周波数をユーザーから入力
cutoff = float(input("Enter the cutoff frequency in Hz: "))

# ローパスフィルタを定義
def low_pass_filter(data, cutoff, fs, order=5):
    nyquist = 0.5 * fs
    normal_cutoff = cutoff / nyquist
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    filtered_data = lfilter(b, a, data)
    return filtered_data

# 音源を読み込む
audio = AudioSegment.from_wav(input_file)

# サンプリングレートとデータを取得
fs = audio.frame_rate
data = np.array(audio.get_array_of_samples())

# ローパスフィルタを適用
filtered_data = low_pass_filter(data, cutoff, fs)

# フィルタリングされたデータをAudioSegmentに変換
filtered_audio = audio._spawn(filtered_data.astype(np.int16).tobytes())

# フィルタリングされた音源を保存
output_file = "/content/filtered_" + input_file
filtered_audio.export(output_file, format="wav")

print(f"Filtered audio saved as {output_file}")

# フィルタリングされた音源をダウンロード
files.download(output_file)

これをgooglecolabなどに貼り付けると使えます。
音源はwavを使ってください。
ファイルを読み込んだらカットオフ周波数を入力してください。
後は自動的にダウンロードされます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?