i have file of raw (audio) data need read r program signed 2-byte integers. c code below conversion after reading in file unsigned char array.
i running difficulties in r, because of unusual integer size of 2 bytes. below c code, wrote have in r @ point, along error messages.
#define bytes_per_sample 2 void samples2floats(unsigned char *audio, float *buff, int n) { int i; (i=0; < n; i++) buff[i] = sample2float(audio + i*bytes_per_sample); } float sample2float(unsigned char *temp) { int i,tot,j,g; unsigned char b[bytes_per_sample],*ptr; float x; tot= 0; ptr = (unsigned char *) &tot; (j = 0; j < bytes_per_sample; j++) ptr[j] = temp[j]; if (tot & 0x8000) tot |= 0xffff0000; x = tot / (float) 0x10000; } return(x); }
r code:
#read in data maxaudio = 100000 to.read = file("filename.raw", "rb") audio = readbin(to.read, "raw", size = 1, n = maxaudio, signed = false) close(to.read) audio[493:500] #what data looks #[1] e9 ff eb ff ef ff ec ff audio = sapply(audio,function(x) paste(as.integer(rev(rawtobits(x))),collapse="")) audio[493:500] #what data looks #[1] "11101001" "11111111" "11101011" "11111111" "11101111" "11111111" "11101100" "11111111" bintodec <- function(x) #convert binary decimal sum(2^(which(rev(unlist(strsplit(as.character(x), "")) == 1))-1)) sample2num = function(char.audio) { wave = numeric(0) (i in 1:length(char.audio)) { p = (i-1)*2 + 1 #concatenates 2 values, e.g. "1110100111111111", converts int int.val = bintodec(paste(tostring(audio[p]), tostring(audio[p+1]), sep = "")) if (bitwand(int.val, 0x8000)) int.val = bitwor(int.val, 0xffff) #had change 0xffff0000 0xffff, or got error warning message: in #bitwor(int.val, 4294901760) : nas introduced coercion integer range x = int.val/0x8000 if (abs(x) > 1) stop(paste("value outside range", temp[1], temp[2], x)) wave = c(wave, x) } return(wave) } test = sample2num(audio[5000:50000]) #error in sample2num(audio[5000:50000]) : # value outside range 1111111111101001 na 1.99996948242188
update: reading in data in r turns out simple as:
audiodata = readbin(name, integer(), 2988032, size = 2)