I am trying to store a song in a database using Python and then retrieve it using Python as well. The song is in MP3 format. However, when I attempt to retrieve the song file, it does not play. Although the audio file was successfully stored in the database, it cannot be retrieved for playback.
Actually I am trying to store the audio file from a particular path and then delete the actual file and then whenever I will need the song I can retrieve it using the python and database but access the audio data without actually downloading it, just get audio data of mp3 as I will play the song using pygame later but it is another story first I have to handle the database thing
Below is the code for storing the file inside database:
import sqlite3
import io
# Connect to the SQLite database (create a new one if it doesn't exist)
conn = sqlite3.connect('audio_database.db')
cursor = conn.cursor()
# Create a table for audio data
cursor.execute('''
CREATE TABLE IF NOT EXISTS audio_data (
id INTEGER PRIMARY KEY,
filename TEXT,
audio_blob BLOB,
duration REAL,
sample_rate INTEGER,
other_info TEXT
)
''')
# Read the MP3 file and store it in a BytesIO object
with open('C:/songs/sample.mp3', 'rb') as mp3_file:
audio_content = mp3_file.read()
audio_blob = io.BytesIO(audio_content)
# Insert sample data (you can replace this with your actual data)
cursor.execute('''
INSERT INTO audio_data (filename, audio_blob, duration, sample_rate, other_info)
VALUES (?, ?, ?, ?, ?)
''', ('sample.mp3', audio_blob.read(), 120.5, 44100, 'Additional text data'))
# Commit changes and close the connection
conn.commit()
conn.close()
Below is the code to retrieve the audio data from the database(it is present in another file):
import sqlite3
import io
import base64
# Connect to the database
conn = sqlite3.connect('audio_database.db')
cursor = conn.cursor()
filename = 'sample.mp3'
# Fetch the audio data
cursor.execute('SELECT audio_blob FROM audio_data WHERE filename = ?', (filename,))
result = cursor.fetchone()
if result:
audio_blob = result[0]
# Create a BytesIO object from the retrieved binary data
audio_bytesio = io.BytesIO(audio_blob)
# Now you can use 'audio_bytesio' as needed (e.g., process or play the audio)
# For example, to decode base64 and save to a file:
with open('retrieved_audio.mp3', 'wb') as output_file:
output_file.write(base64.b64decode(audio_bytesio.read()))
print(f"Audio data for '{filename}' retrieved successfully.")
else:
print(f"Audio data for '{filename}' not found.")
# Close the connection
conn.close()
Also the audio file is not downloading when I open the database in sql web viewer and click save button
Please Help!
Zid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.