我的应用程序需要生成一个音频文件,并且我正在按照我的上一个 Android 版本编写文件生成器。在 Android 上,它使用OKIO来处理 IO,而在 iOS 上,它使用本机 NSData。
每个 WAV 文件都需要一个标头来通知数据读取器(媒体播放器)的一些参数。
它使用这个文件生成器,按照互联网上提供的一些规范写入字节。
//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
它使用这种方法将 Int 写入缓冲区:
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)]
}
在 Android 上,文件正在生成,没有任何问题。但在 iOS 上,这两个参数是错误的。看(大多数顶部文件是在 Android 代码上生成的,底部是由 iOS 代码生成的):
斯威夫特 3
我真的不知道发生了什么,你能帮帮我吗?