This commit is contained in:
yumoqing 2024-08-06 16:04:06 +08:00
parent 984e7e135f
commit 76d3694fa6

View File

@ -15,26 +15,26 @@ def audio_dic2list(audio):
return [audio[k] for k in ks] return [audio[k] for k in ks]
def float32array_to_wav(samples, sample_rate=16000, num_channels=1): def float32array_to_wav(samples, sample_rate=16000, num_channels=1):
# Calculate the total number of samples # Calculate the total number of samples
num_samples = len(samples) num_samples = len(samples)
# Calculate the byte rate # Calculate the byte rate
byte_rate = sample_rate * num_channels * 4 byte_rate = sample_rate * num_channels * 4
# Calculate the block align # Calculate the block align
block_align = num_channels * 4 block_align = num_channels * 4
# Create the WAV header # Create the WAV header
header = struct.pack( header = struct.pack(
'<4sI4s4sIHHIIHH4sI', '<4sI4s4sIHHIIHH4sI',
b'RIFF', 36 + num_samples * 4, b'WAVE', b'fmt ', 16, 3, num_channels, sample_rate, b'RIFF', 36 + num_samples * 4, b'WAVE', b'fmt ', 16, 3, num_channels, sample_rate,
byte_rate, block_align, 32, b'data', num_samples * 4 byte_rate, block_align, 32, b'data', num_samples * 4
) )
# Convert the Float32Array to bytes # Convert the Float32Array to bytes
data = struct.pack('f' * num_samples, *samples) data = struct.pack('f' * num_samples, *samples)
# Write the header and data to a file # Write the header and data to a file
tmpfile = temp_file(suffix='.wav') tmpfile = temp_file(suffix='.wav')
with open(tmpfile, 'w') as f: with open(tmpfile, 'w') as f:
f.write(header) f.write(header)