Save 16 bit signed PCM audio file on Android from BGX device

▼魔方 西西 提交于 2020-12-27 05:56:34

问题


I am working on a mobile application which should be able to read some audio data from a device via Bluetooth. The device has a BGX low energy bluetooth module. There's a very nicely documented framework for BGX on the website of the manufacturer and I successfully managed to connect the device and read the audio data.

The problem is that the BGXService provides me the data in String format, which is an array of chars and char is 16 bit unsigned in Java; However, the audio data that I want to save on the phone is recorded in 16 bit signed PCM on the device. Therefore, I tried to cast the char array into short array and then write into a file. But when I open the generated file with an audio editor software it shows the following image: img of audio data.
As you can see on the picture it looks like the audio file had only positive values; Although, I casted into short int which is signed 16 bit integer. If I play the audio file it sounds like some old, bad quality record. (I am sure the microphone provides good sound quality, it was tested with Matlab.)

Here is the code I use to convert from String to ShortArray (JAVA):

public short[] stringToShortArray(String in){
    short[] ret = new short[in.length()];
    for (int i = 0; i<in.length(); i++){
        ret[i] = (short) in.charAt(i);
    }
    return ret;
}

And I use the following code to generate the raw PCM file (Kotlin):

val fromSB : String = IncomingData.readString() //get raw data

val out = File("int16.pcm")
val output = FileOutputStream(out)
val dos = DataOutputStream(BufferedOutputStream(output))
        
for (i in TypeCast().stringToShortArray(fromSB)) { //convert string to short array
      dos.writeShort(i.toInt()) //the writeShort() function requests Int parameter for some reason
}
        
dos.close()

The task looks pretty easy, but I can't figure out what I do wrong.

来源:https://stackoverflow.com/questions/65184582/save-16-bit-signed-pcm-audio-file-on-android-from-bgx-device

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