1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import wave import numpy as np import pygame # Specify the path to your WAV file wav_file_path = 'D:/temp3/1a-2.wav' wav_file_path = 'D:/projetcs8/Small-talk/sound/1c.wav' output_c_file = 'D:/temp3/audio_data.txt' # Output C header file def play_and_convert_to_c(wav_path, output_path): try: # Open the WAV file with wave.open(wav_path, 'rb') as wav_file: # Read audio data audio_data = wav_file.readframes(-1) # Convert audio data to a NumPy array audio_array = np.frombuffer(audio_data, dtype=np.uint8) # Initialize Pygame for audio playback pygame.init() pygame.mixer.init() # Load the audio data into Pygame mixer pygame.mixer.music.load(wav_path) # Play the audio pygame.mixer.music.play() # Wait for the audio to finish playing while pygame.mixer.music.get_busy(): pass # Write the audio data to a C header file with open(output_path, 'w') as c_file: c_file.write('#ifndef AUDIO_DATA_H\n') c_file.write('#define AUDIO_DATA_H\n\n') c_file.write('#include <stdint.h>\n\n') c_file.write(f'const uint8_t play1[] = {{ {", ".join(map(str, audio_array))} }};\n') c_file.write(f'const int play1_len = {len(audio_array)};\n\n') c_file.write('#endif // AUDIO_DATA_H\n') print(f"Conversion complete. C header file saved to '{output_path}'") except Exception as e: print(f"An error occurred: {str(e)}") # Call the function to play the WAV file, convert to C array, and create the C header file play_and_convert_to_c(wav_file_path, output_c_file) |