Python import pygame does not play an audio - python-3.x

the code just print the name of the song and dont stop after he finish
my code:
import glob
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
I did not use from pygame import *
because it cannot be done in def

Use pygame.mixer.music.stop() when you want to stop the music. The pygame.time.Clock().tick(10) computes the time since it was last called and stalls the program until 1/framerate (in your case framerate=10) seconds have passed. Therefore, your code will run until the song is done playing. If instead you want to pause the program for a set amount of time and stop the music from playing, use time.sleep(), which takes seconds as an argument. Possible example:
import glob
import os
import time
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
time.sleep(10) #sleep for 10 seconds before moving on
pygame.mixer.music.stop()

thank you. i understand now. my mistake was:
pygame.init() -
i need
pygame.mixer.init()

Related

The python program with datetime mofule

I write this code in python in order to read the minute of windows clock and recognize weather it is even or odd and do it 10 times with random sleep time between 5 to 10 seconds:
from datetime import datetime
import random
import time
wait_time = random.randint(5,11)
time.sleep(wait_time)
for i in range(10):
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
But when I run it, sleep time works ok but it show the answer just one time. I think I should write the lines in other arrangement. But I don't know how to fix it.
You need to rearrange your lines according to your own description as below. Same lines but another ordering.
from datetime import datetime
import random
import time
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
for i in range(10):
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
wait_time = random.randint(5,11)
time.sleep(wait_time)

AttributeError: 'str' object has no attribute 'raw_data' (Python Voice Assistant)

Hello guys ı am trying to do desktop voice assistant for ubuntu.In my program ıt was working with
os.system("mpg123 audio.mp3")
How can ı use pydub module instead of this line?
but ı don't want to use system to play audio file for talk with me.I think it's slower. I want faster program and today ı was trying pydub module.
There is my program;
from gtts import gTTS
import speech_recognition as sr
import os
import webbrowser
import datetime
import time
import sys
import random
from pydub import AudioSegment
from pydub.playback import play
#sound = AudioSegment.from_mp3('hello.mp3')
#play(sound)
def talkToMe(audio):
print(audio)
tts = gTTS(text=audio, lang= "en")
tts.save("audio.mp3")
play("audio.mp3") #os.system("mpg123 audio.mp3")
def OurCommands():
r = sr.Recognizer()
with sr.Microphone() as source:
os("clear")
print("Ready for next command")
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration = 1)
audio = r.listen(source)
try:
command = r.recognize_google(audio)
print("You said: " + command + "\n")
except sr.UnknownValueError:
print("Your last command not understand")
command = str(input("Command: "))
return command
#if statements..
def asistan(command):
if "open web browser" in command:
talkToMe("İt\'s opening")
webbrowser.open("www.google.com.tr")
elif "play music" in command:
mixer.init()
mixer.music.load('/path/to/music/')
mixer.music.play()
elif "stop music" in command:
mixer.music.stop()
elif "thank you" in command:
talkToMe("You're welcome")
elif "shutdown my computer" in command:
talkToMe("I will close after five second")
time.sleep(5)
os.system("shutdown now -h")
elif "open youtube" in command:
webbrowser.open("youtube.com")
hour = int(datetime.datetime.now().hour)
if hour >= 1 and hour <12:
talkToMe("Goodmorning")
elif hour >= 12 and hour < 16:
talkToMe("Good afternoon")
else:
talkToMe("Good night")
while True:
asistan(OurCommands())
but when ı want to use pydub module ı get an error like this;
AttributeError: 'str' object has no attribute 'raw_data'
I tried in my computer this module working for me and played mp3 files.
So now how can ı use pydub module in my program for computer to talk with me.
I think ı need audiosegment but how can ı use in my program do ı have to use another module?
or also ı can work with pydub module in my program? Thanks in advance:)
From the docs:
from pydub import AudioSegment
from pydub.playback import play
sound = AudioSegment.from_file("mysound.wav", format="wav")
play(sound)
Play doesn't expect a filename, it expects input like this. You want
sound = AudioSegment.from_file("audio.mp3", format="mp3")
play(sound)

How would I constantly update a variable within a script/program?

I am attempting to make a thermostat of sorts. To do this, I am using a Pi3 with a DHT22 Temperature sensor, and Python3.
What I need is for the temperature to be polled and the corresponding variable to update on its own.
Attempting to do so with any sort of While True: statements results in the gui I'm testing with, not opening.
I'm lost (And yes, this code is hacked together from others. LOL)
#! python3
import time
import RPi.GPIO as GPIO
import string
import tkinter
import tkinter.ttk
import Adafruit_DHT
from tkinter import messagebox
from tkinter import *
root = Tk()
root.title('PiTEST')
root.configure(background='black')
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sensor = Adafruit_DHT.DHT22
pin = 4
def PRINTTEST():
print(temperature, humidity)
TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")
B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
temperature = temperature * 9/5.0 + 32
root.mainloop()
GPIO.cleanup()
Here is a code example without your GPIO things:
#! python3
import time
import string
import tkinter
import random
from tkinter import messagebox
from tkinter import *
root = Tk()
root.title('PiTEST')
root.configure(background='black')
def PRINTTEST():
temperature = random.randint(0,100)
humidity = random.randint(0,100)
print(temperature, humidity)
root.after(1000, PRINTTEST)
TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")
B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)
root.mainloop()
This will print 2 random integers every second in your terminal.

Python add audio to video opencv

I use python cv2 module to join jpg frames into video, but I can't add audio to it. Is it possible to add audio to video in python without ffmpeg?
P.S. Sorry for my poor English
Use ffpyplayer to handle the audio part.
import cv2
import numpy as np
#ffpyplayer for playing audio
from ffpyplayer.player import MediaPlayer
video_path="../L1/images/Godwin.mp4"
def PlayVideo(video_path):
video=cv2.VideoCapture(video_path)
player = MediaPlayer(video_path)
while True:
grabbed, frame=video.read()
audio_frame, val = player.get_frame()
if not grabbed:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
#audio
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
PlayVideo(video_path)
The sample code will work but you need to play around the cv2.waitKey(28) depending on the speed of your video.
This is how I am reading audio and video frames:
from moviepy.editor import *
from pafy import pafy
if __name__ == '__main__':
video = pafy.new('https://www.youtube.com/watch?v=K_IR90FthXQ')
stream = video.getbest(preftype='mp4')
video = VideoFileClip(stream.url)
audio = video.audio
for t, video_frame in video.iter_frames(with_times=True):
audio_frame = audio.get_frame(t)
print(audio_frame)
print(video_frame)
This code downloads YouTube video and returns raw frames as numpy arrays.
You can pass the file as an argument to the VideoFileClip instead of the URL.
You can use pygame for audio.
You need to initialize pygame.mixer module
And in the loop, add pygame.mixer.music.play()
But for that, you will need to choose audio file as well.
However, I have found better idea! You can use webbrowser module for playing videos (and because it would play on browser, you can hear sounds!)
import webbrowser
webbrowser.open("video.mp4")
import pygame
pygame.mixer.init()
pygame.mixer.music.load(
'c:Your_file')
pygame.mixer.music.play()
while True:
pygame.time.Clock().tick()
#used to show that you can do other stuff while playing audio
print("hi")

(PYTHON) How to play audio file again after executing some code with pygame (pyglet or something similar)?

import time, os, sys, pygame
def some_function():
if < condition >:
time.sleep(5)
pygame.mixer.init()
alert = pygame.mixer.Sound('/home/me/alert.wav')
alert.play()
else:
< something >
some_function()
time.sleep(10)
Now here is a problem.
And I tried different combinations with pygame and pyglet.
pyglet.app.run() works but the rest of the script doesn't run!
pygame.mixer.init()
alert = pygame.mixer.Sound('/home/me/alert.wav')
alert.play()

Resources