Playing sound from a specific location in Python Tkinter - python

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

Related

Unable to play WAV file generated by IBM Watson's TTS (Text To Speech)

Currently working with the example script found on IBM Watson's GitHub:
Link: https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/text_to_speech_v1.py
When I run the script, it works perfectly creating the WAV file. However, when I try to play it back within the script, it simply runs and never plays. I tried using PyAudio, Os, Subprocess, and other third party libraries to play the file, however, nothing worked. Is there something I would have to do to the file first before attempting to play it in the script? I'm assuming it has something to do with it being written in binary, which is what the script calls for, but I'm still too new at programming to understand how to solve the problem.
I'll attach my full script below with placeholders for personal info. Thanks!
# coding=utf-8
from os.path import join, dirname
from watson_developer_cloud import TextToSpeechV1
from watson_developer_cloud.websocket import SynthesizeCallback
import subprocess
service = TextToSpeechV1(url='EXAMPLE URL TO API', iam_apikey='EXAMPLE API KEY')
with open(join(dirname(__file__), '..EXAMPLE PATH../resources/output2.wav'),'wb') as audio_file:
response = service.synthesize("What's the weather?", accept='audio/wav', voice="en-US_MichaelVoice").get_result()
audio_file.write(response.content)
def audio_call():
audio_file_path = "..EXAMPLE PATH../resources/output2.wav"
return subprocess.call(["afplay", audio_file_path])
audio_call()
[SOLVED]: Apparently there was a problem with my file directory playing WAV files. By changing the file acceptance to "accept = 'audio/wav'" it worked fine.

how to modify txt file properties with python

I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python

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/

Including sound files in a pygame script using pyinstaller

I am new to programming, so I made myself the challenge to create Pong, and so I did. Now I want to share it with a couple of friends, so I decided to try using pyinstaller (have tried cx_Freeze).
In this Pong game I have 3 sound effects, located in the folder "sfx". So I've looked into including files using pyinstaller, so my .spec file says:
added_files = [
('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitOutline.ogg', 'sfx'),
('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitPaddle.ogg', 'sfx'),
('E:\Game Development Stuff\Python 3\Games\Pong\sfx/score.ogg', 'sfx')
]
a = Analysis(['pong.py'],
pathex=['E:\\Game Development Stuff\\Python 3\\Games\\Pong'],
binaries=None,
datas=added_files,
and in the Pong program itself, I use this code to get the path:
def resource_path(relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
fileDir = os.path.dirname(os.path.realpath('__file__'))
hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))
hitOutline = resource_path(os.path.join(fileDir, "sfx", "hitOutline.ogg"))
score = resource_path(os.path.join(fileDir, "sfx", "score.ogg"))
hitPaddleSound=pygame.mixer.Sound(hitPaddle)
hitOutlineSound=pygame.mixer.Sound(hitOutline)
scoreSound=pygame.mixer.Sound(score)
So I make the exe file using pyinstaller (with the command pyinstaller pong.spec)
but when I open the pong.exe file the command window says:
Traceback "<string>", Unable to open file 'E:\\Game Development Stuff\\Python 3\\Games\\Pong\\dist\\pong\\sfx\\hitPaddle.ogg'
but in that exact same path is hitPaddle.ogg.
It seems to me that pygame isn't able to found it for some weird reason?
I believe the issue is in this line. You are not refrencing the files correctly. You wrote:
hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))
Instead you should of just:
hitpaddle = resource_path("sfx\hitPaddle.ogg")
This is because when you added the files in the spec file, you stated that they should be in "root\sfx" folder. When the .exe is run in onefile mode, all files are actually located in a temp folder called MEIXXXX, with XXXX being some integers. When you run the .exe, if you open this folder you should be able to see your files there.
Solved it for me after struggling with the same issue for hours. Conclusions:
The problem is not in not being able to find it, then it would say something with 'could not find'. It is really an issue with opening the file. Somehow, the .ogg format is giving issues. I changed all my .ogg files to .wav files and my game is running without problems now as executable.
I have no idea why though, because two weeks ago for a previous version I did manage to make a working .exe with the exact same .ogg files. And I don't see how the changes I made should have any effect on this. Anyway, it works now, and perhaps this can also solve this problem for others.

How to use the Windows Explorer or Finder file dialogues in Tkinter/Python2.7.3?

Among other things, I am currently trying to create a basic text editor which can open text files, edit them, and then save them. I have used this Tkinter dialogue for the GUI 'file manager,' but I was wondering if anyone knew the way to access the one that comes default on Windows?
Thanks!
Technical Things:
OS: Windows 7
Language: Python 2.7.3
EDIT 1
By the DEFAULT file dialogue, I mean the windows explorer dialogue:
I also use mac. Assuming that my application is cross-platform, would there be any way for me to have the program check what the os was, and then open either Finder or Windows Explorer.
I need the program to be able to save and open items in different commands. How would I do this?
It's not exactly clear what you're asking, since the one that tkinter comes with is default in Windows. Here's another link for that, just in case you got mixed up somewhere along the line. Remember that you can set it so it only finds a certain type of file, starts in a specific place, returns the filename or directory, or even open the file (I think)
If you mean the Windows Explorer you can open it and close it with pywin32, but not much else. Taken from this answer
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
try importing tkFileDialog:
import tkFileDialog as tkfd
def save():
savenm = tkfd.asksaveasfile()
f = open(savenm.name,"w")
# then put what to do with the opened file
def open():
opennm = tkfd.askopenfile()
f = open(savenm.name,"r")
# then put what to do with the opened file
then make a button that uses the functions:
import Tkinter as tk
root=tk.Tk()
SAVELOADFRAME = tk.Frame(root)
SAVELOADFRAME.pack()
savebtn = Button(SAVELOADFRAME,text="Save",command=save)
savebtn.pack(side=LEFT)
root.mainloop()
loadbtn = Button(SAVELOADFRAME,text="Open",command=open)
loadbtn.pack(side=RIGHT)
maybe if you have a notepad box you might want to insert the text from the file into the tk.Text widget. The above code only works for text based files really (e.g. *.js, *.txt, *.py) not *.exe, *.dll, etcetera.
hope that solves your problem :^)

Categories