I want to play a .wav file in Python 3.4. Additonally, I want python to play the file rather than python open the file to play in VLC, media player etc..
As a follow up question, is there any way for me to combine the .wav file and the .py file into a standalone exe.
Ignore the second part of the question if it is stupid, I don't really know anything about compiling python.
Also, I know there have been other questions about .wav files, but I have not found one that works in python 3.4 in the way I described.
Using pyaudio you may get incorrect playback due to speed, consider instead:
sudo apt-get install python-pygame
Windows:
choco install python-pygame?
def playSound(filename):
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
import pygame
pygame.init()
playSound('hellyeah.wav')
I fixed the problem by using the module pyaudio, and the module wave to read the file.
I will type example code to play a simple wave file.
import wave, sys, pyaudio
wf = wave.open('Sound1.wav')
p = pyaudio.PyAudio()
chunk = 1024
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
data = wf.readframes(chunk)
while data != '':
stream.write(data)
data = wf.readframes(chunk)
If you happen to be using linux a simple solution is to call aplay.
import os
wav_file = "./Hello.wav"
os.system(f'aplay {wav_file}')
Related
I am trying to convert an audio file I have in colab workspace into text using the speech recognition module. But it doesn't work as the audio argument here needs to be audio, how do I load an audio file "audio.wav" into some variable to pass there or just simply pass that file.
import speech_recognition as sr
r = sr.Recognizer()
text = r.recognize_google(audio, language = 'en-IN')
print(text)
The speech_recognition library has a procedure to read in audio files. You can do:
inp = sr.AudioFile('path/to/audio/file')
with inp as file:
audio = r.record(file)
After that pass the audio as the first argument to r.recognize_google()
Here is a good article to understand this library.
pip3 install SpeechRecognition pydub
Make sure you have an audio file in the current directory that contains english speech
import speech_recognition as sr
filename = "16-122828-0002.wav"
The below code is responsible for loading the audio file, and converting the speech into text using Google Speech Recognition:
# initialize the recognizer
r = sr.Recognizer()
# open the file
with sr.AudioFile(filename) as source:
# listen for the data (load audio to memory)
audio_data = r.record(source)
# recognize (convert from speech to text)
text = r.recognize_google(audio_data)
print(text)
This will take few seconds to finish, as it uploads the file to Google and grabs the output
I'm interested in creating a python 3.9 program that streams audio from a YouTube livestream but unfortunately I can't get the video.getbestaudio() function to work and the function only returns the value null. Thus causing the null error on the next line.
Just in case you need to know I'm using the Pafy library to get the audio stream and the python-vlc library to play the audio. The script is also fully functional if I use a YouTube video that is not a livestream or use the video.getbest() function but this also creates a window displaying the video stream which is not what I want.
I was wondering how I could work around the error and create a functioning python script. I am open to use other methods if they properly work. Thanks for any help in advance!
Here is the error:
Traceback (most recent call last):
File "C:\Users\mjten\Desktop\Programing\Python\lofi.py", line 8, in <module>
playurl = best.url
AttributeError: 'NoneType' object has no attribute 'url'
Here is my code:
import pafy
import vlc
url = 'https://www.youtube.com/watch?v=5qap5aO4i9A'
video = pafy.new(url)
best = video.getbestaudio()
playurl = best.url
player = vlc.MediaPlayer(playurl)
player.play()
while True: pass
P.S Sorry for the bad code I'm just trying to figure out a working example in the meantime.
pip install pafy
pip install youtube_dl
import pafy
def stream(url):
video = pafy.new(url, ydl_opts={'nocheckcertificate': True})
print(video)
best = video.getbestaudio()
stream_urls = best.url
print(stream_urls)
stream('https://www.youtube.com/watch?v=5qap5aO4i9A')
I know the title is really vague but anyways, I have a script for downloading the subtitles of a series or movie once the torrent is done downloading. The Input needs to be the filepath of the downloaded file. Conveniently uTorrent has a support for running the script once a torrent finishes downloading and has the filepath as one of its "parameters". I tried running the script with
C:\python\subtitles.py %D
where %D is the supported utorrent parameter for the filepath. This did not work as the script loaded then prompted for user input.Any help on how to automate this would be helpful.
from datetime import timedelta
from babelfish import Language
from subliminal import download_best_subtitles, region, save_subtitles, scan_videos
import os
# configure the cache
region.configure('dogpile.cache.dbm', arguments={'filename': 'cachefile.dbm'})
path = str(input("enter filepath:"))
# scan for videos newer than 1 week and their existing subtitles in a folder
videos = scan_videos(path, age=timedelta(days=7))
print("scan success")
# download best subtitles
subtitles = download_best_subtitles(videos, {Language('eng')})
print("downloads done")
# save them to disk, next to the video
for v in videos:
save_subtitles(v, subtitles[v])
That's because you're trying to get the "parameters" from stdin while your bittorrent client is passing the path as a command-line argument.
Replace path = str(input("enter filepath:")) with
import sys
path = sys.argv[1]
and it'll work.
I am working on a project that requires sound snippets to be played from MP3 files in a playlist. The files are full songs.
I have tried pygame mixer and I can pass the start time of the file, but I cannot pass the end time that I want the music to stop, or be able to fade-in and fade out the current snippet.
I have looked at the vlc and ffmpeg libraries, but I do not see the functionality I am looking for.
I'm hoping someone may be aware of a library out there that may be able to do what I am trying to accomplish.
I finally figured out how to do exactly what I wanted to do!
In the spirit of helping others I am posting an answer to my own question.
My development environment:
Mac OS Mojave 10.14.6
Python 3.7.4
PyAudio 0.2.11
PyDub 0.23.1
Here it is in it's most rudimentary form:
import pyaudio
from pydub import AudioSegment
# Assign a mp3 source file to the PyDub Audiosegment
mp3 = AudioSegment.from_mp3("path_to_your_mp3_file")
# Specify starting and ending offsets from the beginning of the stream
# then apply a fadein and fadeout. All values are in millisecond (seconds * 1000).
mp3 = mp3[int(43000):int(58000)].fade_in(2000).fade_out(2000)
# In the above example the music will start 43 seconds into the track with a 2 second
# fade-in, and only play for 15 seconds with a 2 second fade-out. If you don't need
# these features, just comment out the line and the full mp3 will play.
# Assign the PyAudio player
player = pyaudio.PyAudio()
# Create the stream from the chosen mp3 file
stream = player.open(format = player.get_format_from_width(mp3.sample_width),
channels = mp3.channels,
rate = mp3.frame_rate,
output = True)
data = mp3.raw_data
while data:
stream.write(data)
data=0
stream.close()
player.terminate()
It isn't in the example above, but there is a way to process the stream and increase/decrease/mute the volume of the music.
One other thing that could be done is to set up a thread to pause the processing (writing) of the stream, which would emulate a pause button in a player.
I want to convert any audio file (flac, wav,...) to mp3 with python
I am a noob , I tried pydub but I didn't found out how to make ffmpeg work with it, and If I'm right it can't convert flac file.
The idea of my project is to :
Make musicBee send the path of the 'now playing' track (by pressing the assigned shortcut) to my python file which would convert the music if it is not in mp3 and send it to a folder. (Everything in background so I don't have to leave what I'm doing to make the operation)
You can use the following the code:
from pydub import AudioSegment
wav_audio = AudioSegment.from_file("audio.wav", format="wav")
raw_audio = AudioSegment.from_file("audio.wav", format="raw",
frame_rate=44100, channels=2, sample_width=2)
wav_audio.export("audio1.mp3", format="mp3")
raw_audio.export("audio2.mp3", format="mp3")
You can also look here for more options.
flac_audio = AudioSegment.from_file("sample.flac", "flac")
flac_audio.export("sampleMp3.mp3", format="mp3")