一个裸的PCM格式音频数据,如果不带头信息,不知道其采样率等相关信息,就无法用播放器播放出来。下面是默认的头信息格式:
//音频头部格式
struct wave_pcm_hdr
{
char riff[4]; // = "RIFF"
SR_DWORD size_8; // = FileSize - 8
char wave[4]; // = "WAVE"
char fmt[4]; // = "fmt "
SR_DWORD dwFmtSize; // = 下一个结构体的大小 : 16
SR_WORD format_tag; // = PCM : 1
SR_WORD channels; // = 通道数 : 1
SR_DWORD samples_per_sec; // = 采样率 : 8000 | 6000 | 11025 | 16000
SR_DWORD avg_bytes_per_sec; // = 每秒字节数 : dwSamplesPerSec * wBitsPerSample / 8
SR_WORD block_align; // = 每采样点字节数 : wBitsPerSample / 8
SR_WORD bits_per_sample; // = 量化比特数: 8 | 16
char data[4]; // = "data";
SR_DWORD data_size; // = 纯数据长度 : FileSize - 44
} ;
//默认音频头部数据
struct wave_pcm_hdr default_pcmwavhdr =
{
{ 'R', 'I', 'F', 'F' },
0,
{'W', 'A', 'V', 'E'},
{'f', 'm', 't', ' '},
16,
1,
1,
16000,
32000,
2,
16,
{'d', 'a', 't', 'a'},
0
};
将头信息写入音频数据中:
struct wave_pcm_hdr pcmwavhdr = default_pcmwavhdr;
fwrite(&pcmwavhdr, sizeof(pcmwavhdr) ,1, fp);
while (1)
{
const void *data = QTTSAudioGet(sess_id, &audio_len, &synth_status, &ret);
if (NULL != data)
{
fwrite(data, audio_len, 1, fp);
pcmwavhdr.data_size += audio_len;//修正pcm数据的大小
}
if (synth_status == MSP_TTS_FLAG_DATA_END || ret != 0)
break;
}//合成状态synth_status取值可参考开发文档
//修正pcm文件头数据的大小
pcmwavhdr.size_8 += pcmwavhdr.data_size + 36;
//将修正过的数据写回文件头部
fseek(fp, 4, 0);
fwrite(&pcmwavhdr.size_8,sizeof(pcmwavhdr.size_8), 1, fp);
fseek(fp, 40, 0);
fwrite(&pcmwavhdr.data_size,sizeof(pcmwavhdr.data_size), 1, fp);
fclose(fp);