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
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)
A small adjustment to @gary's answer worked for me:
sound_length <- round(length(sound@left) / sound@samp.rate, 2)