how to stop/close an audio file(mp3/.wav) using python script - python

I wrote code to play an audio file using python, like below.
def playSound(self):
os.system('start C:\\Users\\unavaras\\Music\\223.wav')
time.sleep(10)
It's playing the audio file recursively and it's not being closed untill i manually close it.
Tried below code as well to stop audio, but didn't work
def playSound(self):
p1 = Popen('start C:\\Users\\unavaras\\Music\\223.wav', shell=True)
time.sleep(5)
p1.kill()
In both cases audio is being played recursively.
Can some help me how I can stop the audio after some time or once it finishes playing.

I am using linux but you can try this
def playSound(self):
os.system('timeout 10 start C:\\Users\\unavaras\\Music\\223.wav')
For finding the time duration of audio this link
Get .wav file length or duration

Related

Audio downloaded from youtube_dl python module is encoded in AAC. How to fix it?

So I wanna download some music for our car stereo. Wanted to use an online mp3 converter but the ads are too much. So I made a little piece of code:
import youtube_dl
def mp3_convert():
print('processing...')
link = ['https://youtu.be/LaH9b6Lqwzo']
info = youtube_dl.YoutubeDL().extract_info(url=link, download=False)
file_name = '{}.mp3'.format(info['title'])
options = {
'format' : 'bestaudio/best',
'keepvideo' : False,
'outtmpl' : file_name
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([info['webpage_url']])
print('completed!')
mp3_convert()
Well tbh, it works on pc. It play with Windows' Groove. But it won't play on audacity and the car's stereo. Later on I found this thread which lead me to believe that the problem is because of the AAC encoding as it assumes that I was gonna convert it to mp4(?). Now, is there any chance I could fix it? I mean, I could download it all over again as long as it works.
Ok so I finally found a workaround... Well, it's pretty much the solution. So basically, what I downloaded were mp4 files that are audio-only with a ".mp3" extension. What I described might sound like an mp3 but it isn't.
So what I did was use ffmpeg to convert the mp4 file to mp3. I added something to my code where after it downloads the file, it converts it from mp4 to mp3 with ffmpeg using the subprocess module of python.
subprocess.run(['ffmpeg', '-i', file.mp4, 'file.mp3'])

How to write every x seconds a sound into an audio file (e.g. .mp3) in Python?

Is there a way to write for example every 2 seconds a sound in a (e.g. .mp3 or .wav) file in python?
For example if I have a loop like this
x=0
while x<10:
#write sound.wav into an audio file (file.mp3)
time.sleep(2)
x=x+1
So as a result I want to have an audio file where you hear a sound every 2 seconds (and that for example 10 times)
Thanks in advance
It doesn't work like that. If you sleep(2), the Python interpreter will just idle for 2 seconds and not do anything, i.e. it will pause any file writes and resume after the sleep is over. What you need to do is to write your sound data, then write two seconds of silence (zero-valued samples), then write the sound data again etc.

How to play a sound in a "Hello World" Python program (kids class context)

I'm trying to play a sound in a "Hello World" Python program for a children's class. I used the pygame library for that, but the program can't open the sound file. How can I fix this?
import pygame
pygame.init()
song = pygame.mixer.Sound('robot.wav')
song.play()
print ("Hello, world!")
Error = song = pygame.mixer.Sound('robot.wav')
pygame.error: Unable to open file 'robot.wav'
First of all, after pygame.init() you need pygame.mixer.init(). Second of all, you can't just load files from anywhere. For your program to load robot.wav, you either need to put robot.wav in the same directory as your program file, or you need to specify the entire path to robot.wav. C:/MyPrograms/HelloWorld/robot.wav is an example of a file path, if you are using Windows.
It is also possible that the sound file is corrupted or in the wrong format (e.g. not a wav file, even though it is named .wav).
Refer to:
http://www.pygame.org/docs/ref/mixer.html
http://www.pygame.org/docs/

Python win32com.client pauses from Visio error and does not continue to execute rest of code

I'm opening and archiving Visio files.
visio = comclt.Dispatch("Visio.Application")
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Microsoft Visio")
for i in os.listdir(path): #loops through the path
if i[-3:]=='vsd': #checks to see if it is a visio file
doc = visio.Documents.Open(path+'\\'+i)
But when I open certain Visio files, because the visio file was created on a different machine where a local stencil was present, there is an error of .vss is part of workspace but cannot be opened. This is not a problem, I can just hit ok. So I've put in code to send key ENTER.
Here is my problem. I have the code below. But it does't work because (I think) the code pauses on doc = visio.Documents.Open(path+'\\'+i) and does not continue until ok is pressed. Once I press ok manually, the code sleeps for 2 seconds before continuing.
time.sleep(2)
wsh.AppActivate("Microsoft Visio")
wsh.SendKeys("{ENTER}")
how do I tell python to not wait for doc = visio.Documents.Open(path+'\\'+i)? or is another way to solve this?
You can try to use .AlertResponse to prevent message boxes in Visio:
http://msdn.microsoft.com/en-us/library/office/ff767782.aspx
i.e. before opening the diagram, set
Visio.AlertResponse = 1
This should prevent the message from popping up.

Playing sound from a specific location in Python Tkinter

goal
To play a wav file from the location D:1.wav, when the application is started up by the user
research
Saw the following questions:
How would I go about playing an alarm sound in python?
Play audio with Python
what I tried
I tried the following lines:
Example 1
import winsound
winsound.PlaySound('D:\1.wav',winsound.SND_FILENAME) ##Did not work
Example 2
import winsound
winsound.PlaySound('1.wav',winsound.SND_FILENAME) ##DID not work
Both the times I got the default sound but not the sound that should have played as per the audio file
also
When I write winsound.PlaySound('1.wav',winsound.SND_FILENAME) where does python check for the file 1.wav? In which directory?
Why is the flag winsound.SND_FILENAME used for?
specs Python 2.7 TKinter 8.5 Windows XP SP
Please help me with this issue.
Change
winsound.PlaySound('D:\1.wav',winsound.SND_FILENAME)
to
winsound.PlaySound('D:\\1.wav',winsound.SND_FILENAME)
to prevent python from escaping your path:
>>> a = '\1.wav'
>>> a
'\x01.wav'
winsound.SND_FILENAME
The sound parameter is the name of a WAV file. Do not use with SND_ALIAS.
(From winsound docs)
If you don't use also the flag winsound.SND_NODEFAULT, winsound plays the default sound if it cannot find your specified file.
Create a folder (say D:\test_sounds\) with your wav file inside, add that folder to your PYTHONPATH variable and try running your code again. Or (better, if you plan to distribute your code), following the same post I just linked, add this to your code:
import sys
if "D:\\my_sound_folder" not in sys.path:
sys.path.append("D:\\my_sound_folder")
and then you can just call winsound.PlaySOund('1.wav', winsound.SND_FILENAME) since it will be in your available paths

Categories