About the name: Although this data type has “stream” in its name, you use it in every instance where you need to represent an audio data format in Core Audio—including in non-streamed, standard files. You could think of it as the “audio format basic description” data type. The “stream” in the name refers to the fact that audio formats come into play whenever you need to move (that is, stream) audio data around in hardware or software.
范例中的stream只是表示播放的概念,这里界说的就是iOS音频格式的形貌
获取声音的格式信息
public func audioFormat() -> AudioStreamBasicDescription? {
var size: UInt32 = 0
var audioFile: AudioFileID? // 使用可选类型
var status = AudioFileOpenURL(self.path as CFURL, .readPermission, 0, &audioFile)
// For example, if the data buffer contains 5 bytes of data, with one byte per packet, then the start offset for the last packet is 4. There are 4 bytes in the buffer before the start of the last packet.
var status = AudioFileOpenURL(path as CFURL, .readPermission, 0, &audioFile)
guard status == noErr else {
return
}
let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
/**
Audio Queue(音频队列)是 iOS 或 Mac OS X 中用来 录音 或 播放音频 的软件对象。它由 AudioQueueRef 数据类型表示,在 AudioQueue.h 中声明
音频队列的工作是:
* 连接音频硬件
* 管理内存
* 根据需要,为压缩音频格式使用编解码器
* 调解录音或回放
*/
// 创建输出队列,注册回调函数
status = AudioQueueNewOutput(&format!, playbackCallback, context, nil, nil, 0, &queue)
guard status == noErr else {
print("Create new output queue error")
return
}
status = AudioFileGetProperty(audioFile!, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize)
guard status == noErr else {
print("Get maxPacketSize property error")
return
}
// 计算缓冲区大小
// For uncompressed audio, the value is 1. For variable bit-rate formats, the value is a larger fixed number, such as 1024 for AAC. For formats with a variable number of frames per packet, such as Ogg Vorbis, set this field to 0.
// MP3的值是1152
if format!.mFramesPerPacket != 0 {
// 每秒的包的数量 = 采样率/每个包的帧数
// 比如MP3每秒采样44100次,每个包有1152帧,两者相除就是每秒的包数量
let numPacketsPerSecond = format!.mSampleRate / Double(format!.mFramesPerPacket)