Find duration of wav file in r

♀尐吖头ヾ 提交于 2019-12-23 16:56:49

问题


I know the equation to find the duration of a wav file is:

fileLength/(sampleRate*channel*bits per sample/8)

But I've failed to retrieve all the necessary information to fill this equation in R. Here is an example of what I've come up with:

sound <- readWave(sound.wav) 
sampleRate <- sound@samp.rate #44100
bit <- sound@bit #16

So from the information above I have:

fileLength/(44100*channel*16/8)

The channel will either be 1 or 2, so that I'm not bothered about, but what about the file length? How do I retrieve that in R? Or is there some getDurationWavFile method in some package that I've missed?

Update: I'm using the tuneR library and when I use the str(sound) as suggested it gives me:

Formal class 'Wave' [package "tuneR"] with 6 slots
  ..@ left     : int [1:132301] 0 3290 6514 9605 12502 15145 17482 19464 21052 22213 ...
  ..@ right    : num(0) 
  ..@ stereo   : logi FALSE
  ..@ samp.rate: int 44100
  ..@ bit      : int 16
  ..@ pcm      : logi TRUE

回答1:


Since you know the default summary function (this function is called by default when an object name is typed alone at the command line) for this object type will print out the duration, you can just look at the code for that function to see how it's calculated. The getMethod function will let you peak under the hood:

library(tuneR)

getMethod('summary','Wave')
Method Definition:

function (object, ...) 
{
    l <- length(object@left)
    cat("\nWave Object")
    cat("\n\tNumber of Samples:     ", l)
    cat("\n\tDuration (seconds):    ", round(l/object@samp.rate, 
        2))
    cat("\n\tSamplingrate (Hertz):  ", object@samp.rate)
    cat("\n\tChannels (Mono/Stereo):", if (object@stereo) 
        "Stereo"
    else "Mono")
    cat("\n\tPCM (integer format):  ", object@pcm)
    cat("\n\tBit (8/16/24/32/64):   ", object@bit)
    cat("\n\nSummary statistics for channel(s):\n\n")
    if (object@stereo) 
        print(rbind(left = summary(object@left), right = summary(object@right)))
    else print(summary(object@left))
    cat("\n\n")
}
<environment: namespace:tuneR>

Signatures:
        object
target  "Wave"
defined "Wave"

So to grab the length of your wave file try:

sound_length <- round(sound@left / sound@samp.rate, 2)



回答2:


A small adjustment to @gary's answer worked for me:

sound_length <- round(length(sound@left) / sound@samp.rate, 2)


来源:https://stackoverflow.com/questions/23415036/find-duration-of-wav-file-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!