Code works on Pycharm but gets blocked in the console - python

I've coded a python Youtube to MP3 tool to download youtube mp3s using a keystroke, here's my code:
from pytube import YouTube
from moviepy.editor import *
import os, shutil
import keyboard as kb
def keyboard():
if kb.is_pressed("ctrl+i"):
try:
dl()
except:
pass
def dl():
print("Downloading...")
win32clipboard.OpenClipboard()
url = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
mp4 = YouTube(url).streams.get_highest_resolution().download()
mp3 = mp4.split(".mp4", 1)[0] + ".mp3"
video_clip = VideoFileClip(mp4)
audio_clip = video_clip.audio
audio_clip.write_audiofile(mp3)
audio_clip.close()
video_clip.close()
os.remove(mp4)
shutil.move(mp3, r"C:\Users\eghos\Documents\YouTubeDownloads0")
while True:
keyboard()
When I run it on Pycharm, it works well but when I run it in the terminal, it gets blocked after closing the clipboard.
Thank you for your help

Have you tried running cmd as administrator?

Related

Python smart voice assistant with using a JSON file

I was trying to create a voice assistant using python... but my code is showing some weird texts when I run it... down below is my code
from email.mime import audio
from logging.config import listen
import re
from neuralintents import GenericAssistant
import speech_recognition
import sys
import pyttsx3 as tts
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
speaker.setProperty('rate',150)
def create_note():
global recognizer
speaker.say("What do you want to say?")
speaker.runAndWait()
done=False
while not done:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio= recognizer.listen(mic)
note = recognizer.recognize_google(audio)
note = note.lower()
speaker.say("choose a file name")
speaker.runAndWait
recognizer.adjust_for_ambient_noise(mic, duration=.2)
audio = listen(mic)
filename = recognizer.recognize_google(audio)
filename = filename.lower()
with open(filename,'w' ) as f:
f.write(note)
done= True
speaker.say={f"I saved the note {filename}"}
speaker.runAndWait()
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I dont got that, please say it again")
speaker.runAndWait()
mappings = {'greeting': create_note}
assitant = GenericAssistant('intents.json',intent_methods=mappings)
assitant.train_model()
I expect it to get the input from the mic then go through a JSON file and say the next thing according to the JSON file....
here is the contents of the JSON file
JSON FILE

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.

Mp3 to Wav. convert in Python

I'm currently working on a project where I request a phone call (Mp3) and have to make an automatic transcript through a python script.
I'm using the Azure Speech to text services and got that all working, but that service only supports a Wav. file and I am still stuck at that part.
import azure.cognitiveservices.speech as speechsdk
import time
from os import path
from pydub import AudioSegment
import requests
import hashlib
OID = ***
string = f"***"
encoded = string.encode()
result = hashlib.sha256(encoded)
resultHash = (result.hexdigest())
r = requests.get(f"***", headers={f"***":f"{***}"})
Telefoongesprek = r
# converts audio file (mp3 to Wav.)
#src = Telefoongesprek
#dst = "Telefoongesprek #****.wav"
#sound = AudioSegment.from_mp3(src)
#sound.export(dst, format="wav")
def speech_recognize_continuous_from_file():
speech_config = speechsdk.SpeechConfig(subscription="***", region="***")
speech_config.speech_recognition_language = "nl-NL"
audio_config = speechsdk.audio.AudioConfig(filename="Telefoongesprek #****.wav")
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)
done = False
def stop_cb(evt):
print('CLOSING on {}'.format(evt))
nonlocal done
done = True
all_results = []
def handle_final_result(evt):
all_results.append(evt.result.text)
#speech_recognizer.recognizing.connect(handle_final_result)
speech_recognizer.recognized.connect(handle_final_result)
speech_recognizer.session_started.connect(handle_final_result)
speech_recognizer.session_stopped.connect(handle_final_result)
speech_recognizer.canceled.connect(handle_final_result)
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
speech_recognizer.start_continuous_recognition()
while not done:
time.sleep(.5)
speech_recognizer.stop_continuous_recognition()
print(all_results)
speech_recognize_continuous_from_file()
Thats the code im using without all the keys and encryption, and everthing works apart from the convert from MP3 to Wav.
is there any way I can save the requested file locally in this script and pass it through in:
audio_config = speechsdk.audio.AudioConfig(filename="Telefoongesprek #****.wav"). or do I have to save it to the pc and do it another way.
I have been stuck on this problem for over a week and have tried many different ways.
Thanks in advance!
Beau van der Meer
You should be able to save the response data ( you can access the raw bytes with r.content) to a .mp3 file locally and then pass that file path to pydub.
with open('path/to/local/file.mp3', 'wb') as f:
f.write(r.content)
Another option is to use the module io.BytesIO from the standard library.
If you pass it raw bytes, e g import io; f = io.BytesIO(r.content), it will give you a object that behaves like an open filehandle back, which you can pass to functions accepting files. I didn't check that pydub method you are trying to use accepts filehandles or only paths, so you have to check that first.

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 play mp3 from URL

I'm trying to write a python script that will play mp3 from Soundcloud URL
This is what I've already done:
from urllib.request import urlopen
url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)
data = u.read(1024)
while data:
player.play(data)
data = u.read(1024)
I tried pyaudio with many options like changing formats, channels, rate.
and I just get strange sound from the speakers, I searched Google for pyaudio playing mp3 and didn't found any information.
I tried pygame by creating Sound object by passing the bytes from the mp3 and then just by executing the play function. I am not getting any errors: the script runs but nothing is playing.
I'm working with Python 3 and Ubuntu.
If you happen to have VLC installed (or are willing to install it), then this should work:
import vlc
p = vlc.MediaPlayer("http://your_mp3_url")
p.play()
This has the advantage that it works with everything VLC works with, not just MP3. It can also be paused if you want to.
You can install vlc for python using
pip install python-vlc
Check if you can download file manually using that URL. If its protected site with username/passwd, you may need to take care of that first.
If not, here is a working code that downloads file from url using urllib2 and then plays it using pydub.
Its a two step process where first mp3 file is downloaded and saved to file and then played using external player.
import urllib2
from pydub import AudioSegment
from pydub.playback import play
mp3file = urllib2.urlopen("http://www.bensound.org/bensound-music/bensound-dubstep.mp3")
with open('./test.mp3','wb') as output:
output.write(mp3file.read())
song = AudioSegment.from_mp3("./test.mp3")
play(song)
** Update **
You did mention that you need streaming from web. In that case you may want to look at GStreamer with Python Bindings
Here is a SO link for that.
Sorry but I do not have Python3 to test here, to stream mp3 using pyaudio you will need decode it in PCM data, I know that pymedia can do it, but it is too old and just support python27.
To do this the right way you will need to know some attributes of your audio, things like samplerate, number of channels, bit resolution, to set it in the pyaudio.
I can show how I do it using python27 + pyaudio, first I will show how it is done to stream .wav
from urllib2 import urlopen
#to python3.x
#from urllib.request import urlopen
import pyaudio
pyaud = pyaudio.PyAudio()
srate=44100
stream = pyaud.open(format = pyaud.get_format_from_width(1),
channels = 1,
rate = srate,
output = True)
url = "http://download.wavetlan.com/SVV/Media/HTTP/WAV/NeroSoundTrax/NeroSoundTrax_test4_PCM_Mono_VBR_8SS_44100Hz.wav"
u = urlopen(url)
data = u.read(8192)
while data:
stream.write(data)
data = u.read(8192)
choose large buffer, python is slow in while loop, i did it using chunks of size 8192, note that format, channels and rate are the rigth attributes for this wav file, so for .wav we not need decode, it is a PCM data, now for mp3 we will need decode and put in PCM format to stream.
Lets try using pymedia
from urllib2 import urlopen
import pyaudio
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
dm= muxer.Demuxer( 'mp3' )
pyaud = pyaudio.PyAudio()
srate=44100
stream = pyaud.open(format = pyaud.get_format_from_width(2),
channels = 1,
rate = srate,
output = True)
url = "http://www.bensound.org/bensound-music/bensound-dubstep.mp3"
u = urlopen(url)
data = u.read(8192)
while data:
#Start Decode using pymedia
dec= None
s= " "
sinal=[]
while len( s ):
s= data
if len( s ):
frames= dm.parse( s )
for fr in frames:
if dec== None:
# Open decoder
dec= acodec.Decoder( dm.streams[ 0 ] )
r= dec.decode( fr[ 1 ] )
if r and r.data:
din = r.data;
s=""
#decode ended
stream.write(din)
data = u.read(8192)
This may be secret, because I never saw anyone showing how this can be done in python, for python3 I not know anything that can decode .mp3 into pieces like pymedia do.
Here these two codes are streming and working for .wav and .mp3

Categories