松本涼
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # RでCQT(Constant-Q変換)をやってみる ホクソエムサポーターの松本です。音楽を作ったり聴いたりするのが趣味なので、音楽分析に興味があります。音データの分析にはPythonだとlibrosaというとても便利なパッケージがあるのですが、Rにはそういった汎用的なパッケージがなくてちょっと不便です。 最近ふとRでCQT(Constant-Q変換)をしてみたいと思い、既存のパッケージを使ってできないか探してみたところ特に見つからなかったので、どのように実装すればいいのか調べてみました。 ## スペクトログラムについて 音声や音楽データの分析を行う際には生の波形をそのまま扱うのではなく、スペクトログラム(時間周波数表現)に変換したものを特徴量として利用することがあります。下の画像は「あいうえお」という音声を録音したデータを表したものです。 <style> .sbs { display: flex; justify-content: center; } </style> <ul class="sbs"> <img src="https://i.imgur.com/sWQ6WdV.png" width=55%> <img src="https://i.imgur.com/cU78NVh.png" width=55%> </ul> 左図の波形データは横軸は時間、縦軸は振幅を表します。右図のスペクトログラムは横軸は時間、縦軸は周波数、色はその時間・周波数の成分の強度を表します。 このように視覚化した際、波形データは音の大きさの変化くらいしか分かりませんが、スペクトログラムは周波数ごとにどのように時間変化していくか等が分かります。視覚的に特徴を捉えやすく、画像のようにも扱うことができるので画像処理の手法を応用した分析や変換にも利用しやすいといった利点があります。 スペクトログラムはSTFT(短時間フーリエ変換)によって算出するのが一般的ですが、この方法の問題点として、音高の観点からすると、低域で周波数分解能が低くなるという点があります。人間の聴覚特性として低域では周波数の違いに敏感である(周波数分解能が高い)が、高域になるにつれて鈍感になる(周波数分解能が低くなっていく)という特性があります。音高の国際的な基準はラ(A)=440Hzとなっていますが、1オクターブ上のラは880Hzでちょうど二倍の周波数になります。1オクターブの間には12個の音階があり、これらは公比 $\sqrt[12]{2}$ の等比数列となっています。 STFTでは切り取った信号に対して全ての周波数で同じ窓幅でフーリエ変換を行いますが、CQTではこうした特性を考慮して対数周波数を利用し、かつ周波数ごとに窓幅を変化させて変換することで、音高に対応して周波数分解能を変化させています。 ## 実装 以下ではピアノ演奏を録音した音源を使って、各種プロットを行う例を示します。 <iframe frameborder="0" width="500" height="100" src="https://drive.google.com/file/d/1QmvJmvQhF_zIM4cMdEbAAokyPPX9G8Fg/preview"> </iframe> 音源の読み込みには tuneR パッケージ、スペクトログラムのプロットには seewave パッケージを利用しています。 ```r library(tuneR) library(seewave) # wavファイルの読み込み wav <- readWave("pf.wav") # 波形のプロット plot((seq(wav@left) - 1) * 1 / wav@samp.rate, wav@left, type="l", xlab="time", ylab="amplitude") # STFTによるスペクトログラムのプロット ggspectro(wav, ovlp=50) + scale_y_continuous() + geom_tile(aes(fill=amplitude)) ``` <ul class="sbs"> <img src="https://i.imgur.com/bsXIzVP.png" width=55%> <img src="https://i.imgur.com/dPShHcn.png" width=55%> </ul> <br> 次にCQTを算出してみます。実装はこちらの記事を参考にさせて頂きました。 [音楽プログラミングの超入門(仮): 【Python】 Constant-Q 変換 (対数周波数スペクトログラム)](https://yukara-13.hatenablog.com/entry/2013/12/01/222742) ```r library(signal) # ハミング窓を使うためにsignalパッケージを利用 # パラメータの設定 qrate <- 1 fmin <- 60 fmax <- 6000 bins_per_octave <- 12 hop_length <- 512 two_pi_j <- 2 * pi * 1i # 対数周波数ビンの数とそれらに対応する周波数を算出 nfreq <- round(log2(fmax / fmin) / (1 / bins_per_octave)) + 1 freqs <- fmin * (2 ** ((seq(nfreq) - 1) * (1 / bins_per_octave))) # CQTを行うフレーム数とそれらに対応する時間を算出 nframe <- ceiling(length(wav@left) / hop_length) + 1 times <- seq(nframe) * hop_length * (1 / wav@samp.rate) # 窓幅を設定するためのパラメータ Q <- (1 / ((2 ** (1 / bins_per_octave)) - 1)) * qrate # CQTスペクトログラムのための行列を初期化 ret <- matrix(0, nframe, nfreq) # 周波数ごとに窓幅を変えてCQT for (k in seq(nfreq)) { nsample <- round(wav@samp.rate * Q / freqs[k]) hsample <- round(nsample / 2) phase <- exp(-two_pi_j * Q * seq(nsample) / nsample) weight <- phase * hamming(nsample) # 各フレームごとに信号を切り取る→重みを掛けてretに代入 for (iiter in seq(nframe)){ iframe <- iiter t <- (iframe - 1) * hop_length * (1 / wav@samp.rate) istart <- (iframe - 1) * hop_length - hsample iend <- istart + nsample sig_start <- min(max(1, istart + 1), length(wav@left)) sig_end <- min(max(0, iend), length(wav@left)) win_start <- min(max(1, sig_start - istart), nsample) win_end <- min(max(0, length(wav@left) - istart), nsample) win_slice <- weight[win_start : win_end] y <- sig[sig_start : sig_end] ret[iiter, k] <- sum(y * win_slice) / nsample } } ``` <br> 次に算出したCQTスペクトログラムをggplotを使ってプロットしてみます。実装はseewaveパッケージのggspectroを参考にさせて頂きました。[https://github.com/cran/seewave](https://github.com/cran/seewave) ```r library(ggplot2) P <- abs(t(ret)) # 絶対値に変換し、振幅を取り出す P <- P/max(P) # ノーマライズ P[P == 0] <- .Machine$double.eps # log10(0)で-Infにならないようにする P <- 20*log10(P) # dBスケールに変換 # 外れ値で表示が変にならないように範囲を設定 limit_upper <- 0 limit_lower <- -50 # ggplotで表示するためのデータフレームを作成 frequency <- rep(freqs, times=ncol(P)) time <- rep(times, each=nrow(P)) amplitude <- as.vector(P) amplitude[amplitude < limit_lower] <- limit_lower df <- data.frame(time, frequency, amplitude) tlab <- "Time (s)" flab <- "Frequency (kHz)" alab <- "Amplitude\n(dB)\n" # CQTスペクトログラムのプロット ggplot(df, aes_string(x="time", y="frequency", z = "amplitude")) + xlab(tlab) + ylab(flab) + scale_y_log10(breaks=freqs[seq(1, length(freqs), 12)]) + geom_tile(aes(fill=amplitude)) ``` ![](https://i.imgur.com/g8IwMg4.png) CQTのスペクトログラムの算出とプロットを行うことができました。 プロットを見ると比較的はっきりとピアノで演奏された音が浮き上がっていることが分かります。CQTはメロディーや和音など音楽的な要素の分析によく使われる特徴量で、音楽分析においてはSTFTを使うよりも有用な場合が多いと思います。 ## 参考文献 - 高校数学の美しい物語 - 音階と数学 https://manabitimes.jp/math/1353 - 音楽プログラミングの超入門(仮) - 【Python】 Constant-Q 変換 (対数周波数スペクトログラム) https://yukara-13.hatenablog.com/entry/2013/12/01/222742 - Wizard Notes - 定Q変換 (CQT: Constant-Q Transform) の 解説(音高・コード・メロディの分析向け) https://www.wizard-notes.com/entry/music-analysis/constant-q-transform - seewave ~ an R package dedicated to sound analysis and synthesis ~ https://rug.mnhn.fr/seewave/

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully