R/specgram.R

Defines functions audio2specgram specgram2audio

Documented in audio2specgram specgram2audio

#' audio2specgram
#' Short Term Fourier Transform from time sequence
#' @param x a vector of a time series
#' @param config configuration list generated by stftconfig().
#' @return a matrix of time-frequency representation, where the row is the time and
#'     the column is the frequency. Number of the frequency bins are half of the window size
#'     plus one.
#' @export

audio2specgram <- function(x,config) {
    width <- config$width
    win <- config$towindow(width)
    hwidth <- floor(width/2)
    nshift <- config$frameshift
    nframes <- floor(length(x)/nshift-1)
    specgram <- matrix(0,nrow=nframes,ncol=hwidth+1)
    b <- 1
    for (frm in 1:nframes) {
        w <- x[b:(b+width-1)]*win
        specgram[frm,] <- fft(w)[1:(hwidth+1)]
        b <- b+nshift
    }
    return(specgram)
}

#' specgram2audio
#' Inverse Short Term Fourier Transform from time-frequency representation
#' @param specgram a matrix of a time-frequency representation
#' @param config configuration list generated by stftconfig().
#' @return a vector of time series.
#' @export

specgram2audio <- function(specgram,config) {
    nframe <- nrow(specgram)
    specdim <- ncol(specgram)
    nshift <- config$frameshift
    winlength <- config$width
    win <- config$fromwindow(winlength)
    x <- rep(0,nshift*(nframe+1))
    beginpos <- 1
    spec <- rep(0,winlength)
    for (i in 1:nframe) {
        spec[1:specdim] <- specgram[i,]
        spec[(specdim+1):winlength] <- Conj(specgram[i,(specdim-1):2]);
        wv <- Re(fft(spec,inverse=T))*win/winlength
        x[beginpos:(beginpos+winlength-1)] <- x[beginpos:(beginpos+winlength-1)]+wv;
        beginpos <- beginpos + nshift
    }
    return(x)
}
akinori-ito/audio2specgram documentation built on May 29, 2019, 3:03 a.m.