My app needs to generate a audio file and I'm writing the file generator following my last Android version. On Android it uses OKIO to deal with IO and iOS it uses the native NSData.
Every WAV file needs a header to inform some parameters for the data reader (media player).
It uses this file generator, writing bytes following some specifications provided on the internet.
//Audio file content, this variable will be used
//to storage the audio data (PCM).
var content = [UInt8]() //This is not empty.
var fileSize: Int = 0 //this is not zero.
//Total size of the file, with the header.
let totalFileSize = fileSize + HEADER_SIZE
//Header data
let header = NSMutableData()
//RIFF
header.append([UInt8]("RIFF".utf8), length: 4)
//Size of the entity file
header.append(Data(bytes: readInt(Int32(totalFileSize).littleEndian)))
//WAVE
header.append([UInt8]("WAVE".utf8), length: 4)
//FMT
header.append([UInt8]("fmt ".utf8), length: 4)
//BITRATE
header.append(Data(bytes: readInt(BITRATE.littleEndian)))
//Audio format
var audioFormat = AUDIO_FORMAT_PCM.littleEndian
header.append(&audioFormat, length: 2)
//Number of channels
var audioChannels = CHANNELS.littleEndian
header.append(&audioChannels, length: 2)
//Sample rate
var sampleRate = SAMPLE_RATE.littleEndian
header.append(&sampleRate, length: 4)
//Byte rate
var byteRate = ((SAMPLE_RATE*UInt32(CHANNELS)*UInt32(BYTES_PER_SAMPLE))/UInt32(8)).littleEndian
header.append(&byteRate, length: 4)
//Block align
var blockAlign = (UInt16(CHANNELS) * UInt16(BYTES_PER_SAMPLE) / UInt16(8)).littleEndian
header.append(&blockAlign, length: 2)
//Bytes per sample
var bytesPerSample = BYTES_PER_SAMPLE.littleEndian
header.append(&bytesPerSample, length: 2)
//Data
header.append([UInt8]("data".utf8), length: 4)
//Size of the audio data
var sizeLittleEndian = UInt32(fileSize).littleEndian
header.append(&sizeLittleEndian, length: 4)
print(header.length) //44
It uses this method to write Int on the buffer:
func readInt(_ i: Int32) -> [UInt8] {
return [UInt8(truncatingBitPattern: (i >> 24) & 0xff),
UInt8(truncatingBitPattern: (i >> 16) & 0xff),
UInt8(truncatingBitPattern: (i >> 8) & 0xff),
UInt8(truncatingBitPattern: (i ) & 0xff)]
}
On Android, the file is being generated without any problem. But on iOS these 2 parameters are wrong. Look (Most top file generated on Android code and the bottom was generated by iOS code):
Swift 3
I really don't know what is happening, can you help me?