How to compress WAV file in python? - python

I have converted MP3 files to WAV format but how can I compress WAV file to very small size less or same size that of MP3 size without changing the file format
from pydub import AudioSegment
import os
# files
src_folder = "D:/projects/data/mp3"
dst_folder = "D:/projects/data/wav"
#get all audio file
files = os.listdir(src_folder)
for name in files:
#name of the file
wav_name = name.replace(".mp3", "")
try:
# convert wav to mp3
sound = AudioSegment.from_mp3("{}/{}".format(src_folder, name))
sound.export("{}/{}.wav".format(dst_folder, wav_name), format="wav")
except Exception as e:
pass

s1.export("output.mp3", format='mp3', parameters=["-ac","2","-ar","8000"])
The line of code managed to reduce my audio size by half its previous size. Hope this is helpful to someone

Related

Reg : How to Download YT playlist and convert them compressed Audio file using Python?

Can someone please help me in Downloading a Playlist from YT and compressing them into Audio file please.. I tried with below shown code..
from pytube import YouTube
from pytube import Playlist
from pydub import AudioSegment
import os
import moviepy.editor as mp
import re
YOUTUBE_STREAM_AUDIO = '140' # modify the value to download a different stream
DOWNLOAD_DIR = 'C:\\MyData\\NewAudio'
playlist = Playlist("https://www.youtube.com/watch?v=z9bZufPHFLU&list=PLfqMhTWNBTe0b2nM6JHVCnAkhQRGiZMSJ")
# this fixes the empty playlist.videos list
#playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(playlist.video_urls))
for url in playlist.video_urls:
print(url)
# physically downloading the audio track
for video in playlist.videos:
audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO)
audioStream.download(output_path=DOWNLOAD_DIR)
for file in os.listdir(DOWNLOAD_DIR):
if re.search('mp4', file):
mp4_path = os.path.join(DOWNLOAD_DIR, file)
mp3_path = os.path.join(DOWNLOAD_DIR, os.path.splitext(file)[0] + '.mp3')
new_file = mp.AudioFileClip(mp4_path)
new_file.write_audiofile(mp3_path)
os.remove(mp4_path)
If those warnings are preventing your code to function properly... You'll want to install FFMPEG by either:
Placing ffmpeg.exe in your project's directory
Putting ffmpeg.exe into PATH
You can find downloads for FFMPEG here, and you can find the ffmpeg.exe in the bin folder of the .zip/.7z file downloaded from there.

why audioop causes sound loss for some files?

i am decoding a wav file and trying to convert it to pcm_s16le to i used audioop.adpcm2lin() function but it causes sound loss for some wave files how to fix it ?
import audioop
import struct
import wave
with open(f"game_music.wav","rb") as wb:
types = struct.unpack("4s",wb.read(4))[0]
print(types)
temp = wb.read(2)
temp = wb.read(2)
channels = struct.unpack("H",wb.read(2))[0]
print(channels)
temp = wb.read(2)
sample_rate = struct.unpack("H",wb.read(2))[0]
print(sample_rate)
num_samples = struct.unpack("I",wb.read(4))[0]
print(num_samples)
audio_data = audioop.adpcm2lin(wb.read(),2,None)[0]
with wave.open(f"game_musics.wav", "w") as wav:
wav.setnchannels(channels)
wav.setsampwidth(2)
wav.setframerate(sample_rate)
wav.writeframesraw(audio_data)
for example this file working fine .
https://drive.google.com/file/d/1XAlZZ6bkSRDsnsch6fL2u708xB7xscTa/view?usp=sharing
but this file corrupts .
https://drive.google.com/file/d/1IC8p1TIyEaIi5mwMTWvflCUIhaBaR1BR/view?usp=sharing
if anyone trying to fix then you can use this to test.
its orginal version of corrupted file.
https://drive.google.com/file/d/1OyuwxMSYxiyh1rMFDJ1_k0bRp_hx5CpX/viewusp=sharing
Thanks for helping

How to change a wave.open file to a normal file object without saving the file

I am trying to use the python speech_recognition to get text from a set of frames in a wave file got from a client.
I have tried to use speech_recognition on a wave object but this doesn't work and it only works on files (or the path to a file)
I tried:
import speech_recognition as sr
import wave
r = sr.Recognizer()
# code to get frames
waveFile = wave.open(file, 'wb')
waveFile.setnchannels(1)
waveFile.setsampwidth(2)
waveFile.setframerate(44100)
waveFile.writeframes(frames) # from client
f = sr.AudioFile(waveFile)
with f as source:
audio_file = r.record(source)
text = r.recognize_google(audio_data=audio_file, language="en")
print(text)
Then I get the error:
AssertionError: Given audio file must be a filename string or a file-like object
So I am wondering if there is a way to convert a wave object to a normal file-like object.

Python-Download video from youtube and convert it to mp3

This code downloads the video and convert it to mp3 file. However, the mp3 audio will become 2 times longer than normal video. How can I solve this problem?
import pafy
import os
import moviepy.editor as mp
print "[+] Welcome to Youtube downloader."
download_url = raw_input("URL :")
video = pafy.new(download_url)
best = video.streams
file_name = video.streams[0]
print file_name
directory = "downloaded-music"
if not os.path.exists(directory):
os.makedirs(directory)
x = file_name.download(filepath = directory)
clip = mp.VideoFileClip(x)
print clip.size
clip.audio.write_audiofile(x + ".mp3")
os.remove(x)
It's the value "clip.size" that is twice bigger than the real one, or it's the real lenght of the file ?

How to generate wav with G.711alaw from a mp3 file using pydub library?

I am trying to generate a wav file with G. 711 alaw companding from a mp3 file using Pydub library. The wav file is getting generated but it is not resampled to frequency 8 kHz. I have tried following code:
from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
to_path = '/home/nikhil/Music/m1.wav' #resulted file
from_format = 'mp3'
to_format = 'wav'
params = ["-acodec", "pcm_alaw", "-ar", "8000"]
AudioSegment.from_file(from_path, from_format).export(to_path, format=to_format, parameters=params)
Can someone help me?
I was looking over the code in the export method and I realized that ffmpeg is not used when the output format is "wav".
Since wav is used internally it just writes the in-memory version of the audio directly to disk (this was done to make ffmpeg an optional dependency, if you only need wav support you don't need to install it).
I have 2 ideas that may allow you to get around this issue:
Use a different format kwarg, like "pcm". I'm not sure if this will work, and I don't have ffmpeg on my current machine to test, but definitely worth a try.
from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
to_path = '/home/nikhil/Music/m1.wav' #resulted file
from_format = 'mp3'
to_format = 'pcm'
params = ["-acodec", "pcm_alaw", "-ar", "8000"]
AudioSegment.from_file(from_path, from_format).export(to_path, format=to_format, parameters=params)
Use pydub's internal mechanism for resampling to 8kHz: Again, I can't test this right at the moment...
from_path = '/home/nikhil/Music/m1.mp3' #this is a mp3 file
to_path = '/home/nikhil/Music/m1.wav' #resulted file
seg = AudioSegment.from_mp3(from_path)
seg = seg.set_frame_rate(8000)
seg.export(to_path, format="wav")

Categories