Playing sound in Google Colab - python

Hi so i have code which gives the answer in form of speech. I am using this code:
audio.save("audio.wav")
sound_file = '/content/audio.wav'
Audio(sound_file, autoplay=True)
Now the code plays file all well but if I play in a separate cell. But if I put this code in between my code, it doesn't work. Any ideas?

Wrap it in display():
from IPython.display import Audio, display
display(Audio(sound_file, autoplay=True))

Use this:
from IPython.display import Audio
wn = Audio('path_to_wav_file', autoplay=True)
display(wn)

Related

Python: Progressbar during image import

I have a Python Script, which has to import very large image-files (.tiff, ca. 3GB).
Is there a way to display a progressbar in the command line?
I haven't found a way to measure the progress of an import except for text files.
My current function looks like this:
from skimage import io
def import_tiff(filename):
im = io.imread(filename)
return im
Thank you very much!

Loading audio using pygame.mixer

I used a previous stack overflow post to help me develop the following code:
import os
import pygame
from pygame import *
import sys
GAME_FOLDER = os.path.dirname(__file__)
IMG_FOLDER = os.path.join(GAME_FOLDER, "img")
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(IMG_FOLDER, 'Noota.mp3'))
print("p")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print ("done")
And although the code loads without displaying an error message, it does not play the music; instead all I hear is a 'ticking' noise (about one tick per second). I was wondering if anyone knew why this is happening, and how I can fix it.
For reference, I am using python 3 on a mackintosh computer and the music file does play on the computer when loaded using a media player.
Thank you!
First, you could try loading the audio file as a pygame.mixer.Sound and use SoundName.play() to check if its not mixer.load() that is broken
If it still happens, then its probably an issue with the audio file, go use a universal and up to date format like .ogg so it works on all platforms
Also, time.sleep() may be messing up the sound, as sleep stops every function, and in this case possibly the sound.
Heres an example if you are trying the sound method:
import os
import pygame
from pygame import *
import sys
GAME_FOLDER = os.path.dirname(__file__)
IMG_FOLDER = os.path.join(GAME_FOLDER, "img")
from time import sleep
noota = pygame.mixer.sound(os.path.join(IMG_FOLDER, 'Noota.mp3'))
print("p")
noota.play()
# Maybe the music is being cut off here v
while pygame.mixer.music.get_busy():
sleep(1)
print ("done")

How can I play audio (playsound) in the background of a Python script?

I am just writing a small Python game for fun and I have a function that does the beginning narrative.
I am trying to get the audio to play in the background, but unfortunately the MP3 file plays first before the function continues.
How do I get it to run in the background?
import playsound
def displayIntro():
playsound.playsound('storm.mp3',True)
print('')
print('')
print_slow('The year is 1845, you have just arrived home...')
Also, is there a way of controlling the volume of the playsound module?
I am using a Mac, and I am not wedded to using playsound. It just seems to be the only module that I can get working.
Just change True to False (I use Python 3.7.1)
import playsound
playsound.playsound('storm.mp3', False)
print ('...')
In Windows:
Use winsound.SND_ASYNC to play them asynchronously:
import winsound
winsound.PlaySound("filename", winsound.SND_ASYNC | winsound.SND_ALIAS )
To stop playing
winsound.PlaySound(None, winsound.SND_ASYNC)
On Mac or other platforms:
You can try this Pygame/SDL
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
There is a library in Pygame called mixer and you can add an MP3 file to the folder with the Python script inside and put code like this inside:
from pygame import mixer
mixer.init()
mixer.music.load("mysong.mp3")
mixer.music.play()
Well, you could just use pygame.mixer.music.play(x):
#!/usr/bin/env python3
# Any problems contact me on Instagram, #vulnerabilties
import pygame
pygame.mixer.init()
pygame.mixer.music.load('filename.extention')
pygame.mixer.music.play(999)
# Your code here
A nice way to do it is to use vlc. Very common and supported library.
pip install python-vlc
Then writing your code
import vlc
#Then instantiate a MediaPlayer object
player = vlc.MediaPlayer("/path/to/song.mp3")
#And then use the play method
player.play()
#You can also use the methods pause() and stop if you need.
player.pause()
player.stop
#And for the super fancy thing you can even use a playlist :)
playlist = ['/path/to/song1.mp3', '/path/to/song2.mp3', '/path/to/song3.mp3']
for song in playlist:
player = vlc.MediaPlayer(song)
player.play()
You could try just_playback. It's a wrapper I wrote around miniaudio that plays audio in the background while providing playback control functionality like pausing, resuming, seeking and setting the playback volume.
from pygame import mixer
mixer.music.init()
mixer.music.load("audio.mp3") # Paste The audio file location
mixer.play()
Use vlc
import vlc
player = None
def play(sound_file):
global player
if player is not None:
player.stop()
player = vlc.MediaPlayer("file://" + sound_file)
player.play()
This is a solution to reproduce similar length sounds. This solution worked to me to solve the error:
The specified device is not open or recognized by MCI.
Here follow the syntax as a class method, but you can change it to work even without a class.
Import these packages:
import multiprocessing
import threading
import time
Define this function:
def _reproduce_sound_nb(self, str_, time_s):
def reproduce_and_kill(str_, time_sec=time_s):
p = multiprocessing.Process(target=playsound, args=(str_,))
p.start()
time.sleep(time_sec)
p.terminate()
threading.Thread(target=reproduce_and_kill, args=(str_, time_s), daemon=True).start()
In the main program/method:
self._reproduce_sound_nb(sound_path, 3) # path to the sound, seconds after sound stop -> to manage the process end
I used a separate thread to play the sound without blocking the main thread. It works on Ubuntu as well.
from threading import Thread
from playsound import playsound
def play(path):
"""
Play sound file in a separate thread
(don't block current thread)
"""
def play_thread_function:
playsound(path)
play_thread = Thread(target=play_thread_function)
play_thread.start()

Python gtts vlc plays too quickly to hear the first couple words

In python, using the module gTTS and VLC-python, I've created a Text to speech program, which is quite simple to do.
But the thing which is bugging me is when I get to playing the mp3 file created by gTTS it skips the first word or two.
So if I have the string "The weather today will be cloudy". It'll speak out "today will be cloudy"
Even if I adjust the string, it seems to miss out the first word or two, sometimes it starts mid word.
When I play the audio file outside of the code, it plays normally, sometimes it stutters on the first word but if I rewind and have it wait a second, it plays perfectly.
Is there a way to load the audio clip or buffer it before playing so it starts smoothly?
In your code you are going to have something along the lines of:
self.Media = self.Instance.media_new_path('my.mp3')
self.player.set_media(self.Media)
self.player.set_xwindow(self.panel1.GetHandle())
which defines what is going to be played.
Then you will have something like:
if self.player.play() == -1:
print("Error playing file")
else:
pass
where you tell vlc to start playing the file.
put a time.sleep(3) before that play command or actuate the play function from a separate button or something.
This is the equivalent of the:
vlc --no-playlist-autostart vp.mp3
or
vlc --start-paused vp.mp3 command line options.
i.e. load the file but don't start playing it, until I tell you.
I found another library called playsound which plays the audio files back without any clipping:
from gtts import gTTS
from playsound import playsound
text = "Say something."
speech = gTTS(text = text, lang = 'en', slow = False)
mp3_file = 'text.mp3'
speech.save(mp3_file)
playsound(mp3_file)
I think this is a better solution than VLC, even if there was no clipping of audio in VLC, because using the vlc library requires you to have VLC Media Player installed on your computer, whereas this playsound library doesn't require you to install anything else for it to work.

What is preventing the sound files from being played in this pygame Mixer set up?

I'm trying to write a small bit of code to play music files in the background of a game. The problem I'm coming across is that despite all the code being laid out and phrased properly no sound files will play. I put several print statements in the code and it seems to suggest that the sound file is either not loading or is simply not playing once it loads?
import pygame
def musicPlayer():
print "Playing music now"
pygame.init()
pygame.mixer.music.load('01ANightOfDizzySpells.mp3')
print "load song1"
pygame.mixer.music.play(loops=0, start=0.0)
print "play song1"
pygame.mixer.music.queue('01HHavok-intro.mp3')
pygame.mixer.music.queue('02HHavok-main.mp3')
pygame.mixer.music.queue('02Underclockedunderunderclockedmix.mp3')
pygame.mixer.music.queue('03ChibiNinja.mp3')
pygame.mixer.music.queue('04AllofUs.mp3')
pygame.mixer.music.queue('05ComeandFindMe.mp3')
pygame.mixer.music.queue('06Searching.mp3')
pygame.mixer.music.queue('07WeretheResistors.mp3')
pygame.mixer.music.queue('08Ascending.mp3')
pygame.mixer.music.queue('09ComeandFindMe-Bmix.mp3')
pygame.mixer.music.queue('10Arpanauts.mp3')
pygame.mixer.music.queue('DigitalNative.mp3')
pygame.mixer.music.set_endevent()
#musicPlayer()
musicPlayer()
Am I missing something basic? Or could it have to do with my computer not the code?
Edit: this is the output from running the code
Playing music now
load song1
play song1
As you can see it throws no errors.
I tried your code with a mid file, it works fine, but there's some adjustments:
import pygame
def musicPlayer():
pygame.init()
pygame.mixer.music.load('test.mid')
print "load song1"
pygame.mixer.music.play()
print "play song1"
pygame.mixer.music.queue('test_2.mid')
musicPlayer()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
print "DONE"
if the script ends the play won't happend, for that you need to get_busy() in a while loop.
in the documentation of pygame.music it states: Be aware that MP3 support is limited [...] Consider using OGG instead.
I played a little with the Sound class.
Here's what I came up:
import pygame
def musicPlayer():
pygame.mixer.init()
channel = pygame.mixer.Channel(1)
sound = pygame.mixer.Sound('test.ogg')
channel.play(sound)
musicPlayer()
while pygame.mixer.get_busy():
pygame.time.Clock().tick(10)
print "DONE"
I'm not very familiar with pygame and its methods, but my guess is that either it cannot find the file correctly, or it's not able to correctly handle the file that it finds.
I would suggest putting the full path to audio files to see if that helps. That would rule out the issue of it not finding the files properly (although hardcoding this is obviously not a good idea long-term as any changes you make to the organizational structure of your program will likely break those paths).
And according to their documentation, their MP3 support is limited. You might try using .ogg files instead (http://www.pygame.org/docs/ref/music.html) as it could just be an issue with the encoding not being fully supported.

Categories

Resources