-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInAudio.py
66 lines (57 loc) · 2.39 KB
/
InAudio.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# wave module comes with standard python installation
import wave
from os import path
from pydub import AudioSegment
def convert(infile,outfile):
# convert mp3 file to wav file
sound = AudioSegment.from_mp3(infile)
sound.export(outfile, format="wav")
def embed(infile: str, message: str, outfile: str):
song = wave.open(infile, mode='rb')
# Read frames and convert to byte array
frame_bytes = bytearray(list(song.readframes(song.getnframes())))
# Append dummy data to fill out rest of the bytes. Receiver shall detect and remove these characters.
message = message + int((len(frame_bytes) - (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):
frame_bytes[i] = (frame_bytes[i] & 254) | bit
frame_modified = bytes(frame_bytes)
# Write bytes to a new wave audio file
with wave.open(outfile, 'wb') as fd:
fd.setparams(song.getparams())
fd.writeframes(frame_modified)
song.close()
return outfile
def extract(file: str):
"""This function takes the filepath and decodes the hidden data and returns it"""
song = wave.open(file, mode='rb')
# Convert audio to byte array
frame_bytes = bytearray(list(song.readframes(song.getnframes())))
# Extract the LSB of each byte
extracted = [frame_bytes[i] & 1 for i in range(len(frame_bytes))]
# Convert byte array back to string
message = "".join(chr(int("".join(map(str, extracted[i:i+8])), 2)) for i in range(0, len(extracted), 8))
# Cut off at the filler characters
decoded = message.split("###")[0]
song.close()
return decoded
# Main Function
def main():
a = int(input(":: Welcome to Steganography ::\n1. Encode\n2. Decode\n"))
if (a == 1):
host = input("Enter audio file name(with extension) : ")
secret = input("Enter data to be encoded : ")
output = input("Enter the name of new audio(with extension) : ")
embed(host,secret,output)
elif (a == 2):
host = input("Enter audio file name(with extension) : ")
print("Decoded Word : " + extract(host))
else:
raise Exception("Enter correct input")
# Driver Code
if __name__ == '__main__' :
#Write test cases
# main()
pass