# We will use wave package available in native Python installation to read and write .wav audio file
import wave
# read wave audio file
audio = wave.open("Ex3_sound5.wav", mode='rb')
# Read frames and convert to byte array
dataSamplesByteArray = bytearray(list(audio.readframes(audio.getnframes())))
# The "secret" text message
message = 'Father Christmas does not exist'
# Append dummy data to fill out rest of the bytes. Receiver shall detect and remove these characters.
message = message + int((len(dataSamplesByteArray)-(len(message)*8*8))/8) *'#'
# Convert text to bit array
bits = list(map(int, ''.join([bin(ord(i)).lstrip('0b').rjust(8,'0') for i in message])))
# Replace LSB of each byte of the audio data by one bit from the text bit array
for i, bit in enumerate(bits):
dataSamplesByteArray[i] = (dataSamplesByteArray[i] & 254) | bit
# Get the modified bytes
dataSamplesBytes = bytes(dataSamplesByteArray)
# Write bytes to a new wave audio file
with wave.open('Ex3_sound5_msg.wav', 'wb') as fd:
fd.setparams(audio.getparams())
fd.writeframes(dataSamplesBytes)
audio.close()
print("Audio has been encoded with the hidden message and saved as Ex3_sound5_msg.wav")
Audio has been encoded with the hidden message and saved as Ex3_sound5_msg.wav
# Open the encoded audio file using wave
import wave
audio = wave.open("Ex3_sound5_msg.wav", mode='rb')
# get the audio data
dataPoints = bytearray(list(audio.readframes(audio.getnframes())))
# Get the LSB of each byte using the bitwise method
lsbs = [dataPoints[i] & 1 for i in range(len(dataPoints))]
# add the lsbs together into pairs of 8 so that they can be converted into asci characters
asciChr = "".join(chr(int("".join(map(str,lsbs[i:i+8])),2)) for i in range(0,len(lsbs),8))
# We can already see the message here, but need to remove the # characters at the end of the string
# print(asciChr[:50])
# split the text based on the # character and save the 1st section of the split
msg = asciChr.split("#")[0]
# Print the hidden message
print(msg)
audio.close()
Father Christmas does not exist