2018-09-10 09:13:47 -04:00
|
|
|
from __future__ import print_function
|
2021-01-25 21:49:01 -05:00
|
|
|
|
2017-08-23 11:12:56 -04:00
|
|
|
import os
|
|
|
|
import struct
|
2021-01-25 21:49:01 -05:00
|
|
|
import wave
|
|
|
|
from builtins import range
|
2017-08-23 11:12:56 -04:00
|
|
|
|
2018-12-04 02:32:48 -05:00
|
|
|
|
2017-08-23 11:12:56 -04:00
|
|
|
def get_wave_array_str(filename, target_bits):
|
2021-01-25 21:49:01 -05:00
|
|
|
wave_read = wave.open(filename, 'r')
|
|
|
|
array_str = ''
|
2017-08-23 11:12:56 -04:00
|
|
|
nchannels, sampwidth, framerate, nframes, comptype, compname = wave_read.getparams()
|
|
|
|
sampwidth *= 8
|
|
|
|
for i in range(wave_read.getnframes()):
|
2021-01-25 21:49:01 -05:00
|
|
|
val, = struct.unpack('<H', wave_read.readframes(1))
|
2017-08-23 11:12:56 -04:00
|
|
|
scale_val = (1 << target_bits) - 1
|
|
|
|
cur_lim = (1 << sampwidth) - 1
|
2018-12-04 02:32:48 -05:00
|
|
|
# scale current data to 8-bit data
|
2017-08-23 11:12:56 -04:00
|
|
|
val = val * scale_val / cur_lim
|
2018-09-10 09:13:47 -04:00
|
|
|
val = int(val + ((scale_val + 1) // 2)) & scale_val
|
2021-01-25 21:49:01 -05:00
|
|
|
array_str += '0x%x, ' % (val)
|
2017-08-23 11:12:56 -04:00
|
|
|
if (i + 1) % 16 == 0:
|
2021-01-25 21:49:01 -05:00
|
|
|
array_str += '\n'
|
2017-08-23 11:12:56 -04:00
|
|
|
return array_str
|
|
|
|
|
2018-12-04 02:32:48 -05:00
|
|
|
|
|
|
|
def gen_wave_table(wav_file_list, target_file_name, scale_bits=8):
|
2021-01-25 21:49:01 -05:00
|
|
|
with open(target_file_name, 'w') as audio_table:
|
2018-09-10 09:13:47 -04:00
|
|
|
print('#include <stdio.h>', file=audio_table)
|
|
|
|
print('const unsigned char audio_table[] = {', file=audio_table)
|
2017-08-23 11:12:56 -04:00
|
|
|
for wav in wav_file_list:
|
2021-01-25 21:49:01 -05:00
|
|
|
print('processing: {}'.format(wav))
|
2018-12-04 02:32:48 -05:00
|
|
|
print(get_wave_array_str(filename=wav, target_bits=scale_bits), file=audio_table)
|
2018-09-10 09:13:47 -04:00
|
|
|
print('};\n', file=audio_table)
|
2021-01-25 21:49:01 -05:00
|
|
|
print('Done...')
|
2017-08-23 11:12:56 -04:00
|
|
|
|
2018-12-04 02:32:48 -05:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2021-01-25 21:49:01 -05:00
|
|
|
print('Generating audio array...')
|
2017-08-23 11:12:56 -04:00
|
|
|
wav_list = []
|
2021-01-25 21:49:01 -05:00
|
|
|
for filename in os.listdir('./'):
|
|
|
|
if filename.endswith('.wav'):
|
2017-08-23 11:12:56 -04:00
|
|
|
wav_list.append(filename)
|
2021-01-25 21:49:01 -05:00
|
|
|
gen_wave_table(wav_file_list=wav_list, target_file_name='audio_example_file.h')
|