How to quit VLC after playing a mp3 file - python

I have this function and I need to close the file before exiting the function say("some text").
def say(self, text):
tts = gTTS(text, lang='fr')
file="text.mp3"
tts.save(file)
audio = MP3(file)
p = vlc.MediaPlayer(file)
p.play()
time.sleep((audio.info.length)) #to avoid it listening to itself
p.stop()
return file
Because If I don't do this, I have this error
OS Error: [Errno -9993] Illegal combination of I/O device
I think that this error occurs because I'm trying to listen just after the call of the function say and the file is still open.
nb: I'm working with Python 3

Though i am not to experienced with TTS, shouldnt it work if you just do close(os.getcwd()+'/'+file)?

Related

MicroPython PyCharm 2021.3.3 plugin permission error

I was trying to set up MicroPython on PyCharm 2021.3.3, unfortunately I was not able to successfully connect my board to IDE. I'm getting trying to use tools>>MicroPython>>MicroPython REPL:
Found the device, but could not connect via port 'COM4': could not open port 'COM4': PermissionError(13, 'Odmowa dostępu.', None, 5)
I'm not sure what to suggest. :-(
Press ENTER to continue
Then I have tried to flush simple program to control despite previous error and it spits out:
Connecting to COM4
Traceback (most recent call last):
File "C:\Users\reczul\AppData\Roaming\JetBrains\PyCharm2021.3\plugins\intellij-micropython\scripts\microupload.py", line 139, in <module>
main(sys.argv[1:])
File "C:\Users\reczul\AppData\Roaming\JetBrains\PyCharm2021.3\plugins\intellij-micropython\scripts\microupload.py", line 56, in main
board = Pyboard(port)
File "C:\Users\reczul\PycharmProjects\pythonProject1\venv\lib\site-packages\ampy\pyboard.py", line 147, in __init__
raise PyboardError('failed to access ' + device)
ampy.pyboard.PyboardError: failed to access COM4
What can I do to fix this error?
The sample code I have used:
from machine import Pin, Timer
led = Pin(25, Pin.OUT)
tim = Timer()
def tick(timer):
global led
led.toggle()
tim.init(freq=2.5, mode=Timer.PERIODIC, callback=tick)```
Assuming you are using a Pi Pico.
You are most likely getting this error because you pressed the 'BOOTSEL' button while plugging your device in.
Drag your UF2 file onto the device, it should reboot.
Don't unplug the device and hold the 'BOOTSEL' this time.
It should be good to go now.

How do I send pydub audio segment raw data using discord.py to a voice channel? I get error, hear nothing or gibberish noise depending on parameters

As the title says, I've been trying to send chunks audio data using discord.py to a voice channel. So using pydub I basically load an mp3 file (and playback works so file is ok), make chunks, send them as packages.
And then I tried to convert the mp3 file to opus file. It's playing too. Both files are ok.
There are a few stuff:
So the issue is, after I make the raw audio chunks list and try to send each element in it:
a) With Encode=True, I get an error about NoneType object not having encode attribute.
b) With Encode=False, it actually sends the data but I don't hear anything at all.
c) With Encode=False, but when loading the mp3 file with additional codec="opus" parameter, I hear gibberish noise. So it's not for conversion i guess okay...
d) With Encode=False, but when loading the opus file with additional codec="opus" parameter (without that codec="opus" i cant play the audio anyway), it's still the NoneType error.
-I have all the 3 executables (ffmpeg.exe, ffplay.exe and ffprobe.exe) in the same directory as the script. But not in PATH. (Didn't tell me anything about it and playback worked, plus i heard the gibberish noise too at least so no problem here)
-I also have m1.mp3 and m1.opus in the same directory as the script. It's ok.
-There are no subdirectories or anything else.
-I have PyNaCl and discord.py[audio] installed.
I don't know where I'm doing wrong. What kind of data was i supposed to send if not this? Can I encode the raw audio myself to opus without too much work and definitely not saving a file even if it is temp?
I don't want to just load the mp3 file all at once and play, I need to be able to make chunks. I don't want to save these chunks anywhere either.
Here is the code:
import discord
import pydub
import os
from pydub.utils import make_chunks
import asyncio
TOKEN = ":("
base_path = os.getcwd()
pydub.AudioSegment.ffmpeg = os.path.join(base_path, "ffmpeg.exe")
pydub.AudioSegment.ffprobe = os.path.join(base_path, "ffprobe.exe")
pydub.AudioSegment.ffplay = os.path.join(base_path, "ffplay.exe")
pydub.AudioSegment.converter = os.path.join(base_path, "ffmpeg.exe")
#audio = pydub.AudioSegment.from_file(os.path.join(base_path, "m1.mp3"), format="mp3")#, codec="opus")
audio = pydub.AudioSegment.from_file(os.path.join(base_path, "m1.opus"), codec="opus") #dont add format="opus". format isnt extension ig. https://github.com/jiaaro/pydub/issues/257
#audio = pydub.AudioSegment.from_file(os.path.join(base_path, "m1.opus")) #didnt hear anything at all evn with play(audio) below.
audio = audio[:9*1000] #first 9 seconds
#let me be sure that it actually plays.
from pydub.playback import play #needs simpleaudio to work idk...
play(audio)
chunks = make_chunks(audio, (1/20)*1000)
client = discord.Client()
#client.event
async def on_ready():
print("Ready.")
#client.event
async def on_message(message):
if message.content.startswith(",test"):
#connect to vc
vp = await message.author.voice.channel.connect()
#i tried with chunk._data as well. they are same anyway.
chunks_raw = [chunk.raw_data for chunk in chunks]
#print(chunks_raw == [chunk._data for chunk in chunks]) #it's True
print("Sending?")
for i, chunk in enumerate(chunks_raw, start=1):
vp.send_audio_packet(chunk, encode=True) #false --> not heard, true --> weird error (that occurs no matter if i have codec="opus" or not)
print("Sent", i, "out of", len(chunks), "chunks.")
await asyncio.sleep(1/20)
vp.cleanup()
await vp.disconnect()
await message.channel.send("Playback is over.")
client.run(TOKEN)
so if encode=True i get this (and i have no idea why):
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\h\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\h\Desktop\randomly lying pys\bas\broken_audio_showcase.py", line 38, in on_message
vp.send_audio_packet(chunk, encode=True) #false --> not heard, true --> weird error
File "C:\Users\h\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\voice_client.py", line 633, in send_audio_packet
encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)
AttributeError: 'NoneType' object has no attribute 'encode'
and if encode=False i can see "Sent i out of len(chunks) chunks" in console, yet i cant hear anything. I also see "Playback is over" message when it ends so it actually sends something...
if i go ahead and change the voice_client.py myself to add this to the first line of send_audio_packet function:
self.encoder = opus.Encoder() #manually added
and then i set encode to True, then it actually sends a hearable voice. of course its gibberish again, but at least i hear something from discord voice chat.
can anyone actually help me with this?
Well I knew sound would be confusing, but never expected it to be this hard. I have no idea what counts as opus if not an opus file itself that's been converted via ffmpeg, not by literally changing the extension or anything.

Can't initialize ANT+ Node with Python OpenANT library

I've totally new in Python and also in the ANT+ technology. I wonder if that's not some basic problem, but I've been strugling with it for couple of days already browsing through forums with no luck..
So I'm trying to use the Python OpenANT library (https://github.com/Tigge/openant) to access my ANT doungle which is plugged into the USB port (WINDOWS 10 PRO). My goal is to access my Garmin through it and get some data from it. However, I'm stuck at the very beginning trying to inizialize the ANT Node. My code is this:
from ant.easy.node import Node
node=Node()
To this I get the exception:
File "C:/Users/Edgars/Desktop/untitled-5.py", line 2, in <module>
pass
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\ant\easy\node.py", line 56, in __init__
self.ant = Ant()
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\ant\base\ant.py", line 68, in __init__
self._driver.open()
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\ant\base\driver.py", line 193, in open
cfg = dev.get_active_configuration()
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\core.py", line 909, in get_active_configuration
return self._ctx.get_active_configuration(self)
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\core.py", line 113, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\core.py", line 250, in get_active_configuration
bConfigurationValue=self.backend.get_configuration(self.handle)
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\backend\libusb0.py", line 519, in get_configuration
ret = self.ctrl_transfer(
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\backend\libusb0.py", line 601, in ctrl_transfer
return _check(_lib.usb_control_msg(
File "C:\Users\Edgars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pyusb-1.1.0-py3.8.egg\usb\backend\libusb0.py", line 447, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed, win error: A device which does not exist was specified.\r\n\n'
I have closed the Garmin Agent, so no other programs are using my ANT dongle at the same time. When I run my code, the specific sound occurs every time - the one that we hear when we detach a USB device by selecting "Eject" from the drop-down menu (the sound happens simultaneously with the exception message), so I guess the USB gets accessed at some moment.
Before the exception I get such a printout:
Driver available: [<class 'ant.base.driver.SerialDriver'>, <class 'ant.base.driver.USB2Driver'>, <class 'ant.base.driver.USB3Driver'>]
- Using: <class 'ant.base.driver.USB3Driver'>
Could not check if kernel driver was active, not implemented in usb backend
I have seen other users' threads where the printout says Using ... USB1Driver or Using ... USB2Driver, and they don't get this message. I've installed various python libraries trying to get even this far, and now I've worried that maybe they get in each other's way.. Can anybody help me with this? It's really frustrating that a program of only two code lines can get so complicated.. :D
!!!EDIT!!!
OK, I found the problem - in the "driver.py" file there's a line dev.reset() which disconnects my USB dongle before trying to access it. I have no idea why such a line should exist there. I tried to comment this line out, and now I'm not getting the abovementioned error anymore. However, what happens now is there are continuos timeouts..
So my code has evolved to this (although actually the same timeouts happen also with my initial 2-lines-long program):
from ant.easy.node import Node
from ant.easy.channel import Channel
from ant.base.message import Message
import threading
NETWORK_KEY=[0xb9,0xa5,0x21,0xfb,0xbd,0x72,0xc3,0x45]
def on_data(data):
print("Data received")
print(data)
def back_thread(node):
node.set_network_key(0x00,NETWORK_KEY)
channel=node.new_channel(Channel.Type.BIDIRECTIONAL_RECEIVE)
channel.on_broadcast_data=on_data
channel.on_burst_data=on_data
channel.set_period(16070)
channel.set_search_timeout(20)
channel.set_rf_freq(57)
channel.set_id(0,120,0)
try:
channel.open()
node.start()
finally:
node.stop()
print("ANT Node Shutdown Complete")
node=Node()
x=threading.Thread(target=back_thread,args=(node,))
x.start()
Now I get this error line printed out for ever:
<class 'usb.core.USBError'>, (None, b'libusb0-dll:err [_usb_reap_async] timeout error\n')
When my Garmin Agent is active, I get the error "ANT resource already in use" instead of the timeout, so I'm certain that my code is accessing the ANT dongle.. However, now (having closed the Garmin Agent) I have no idea about how to get rid of the timeout and how to establish a simple handshake with my Garmin device..
OK, now I've figured out that my Garmin Forerunner 310XT can't act as a data source and thus cannot be accessed using the ANT+ protokol. Instead, I should use the ANT-FS protocol of File Sharing. Keeping my head down and trying it out...
I posted a PR with some changes that I made to get Tigge’s openant library to work. Basically, I put a pause after the reset line that you mentioned above and bypassed the use of udev_rules as it doesn’t apply in Windows. You can use libusb but installation is a bit different. I’ve added Windows installation instructions to the readme in the PR with details on what worked for me.

Speech recognition: microphone working in software but not in Python code

I am using an external sound card with a built-in microphone for voice recognition on a Raspberry Pi 3 model B. The issue is that when I run the code the code executes but then stops on "SAY SOMETHING". When I terminate the code I get these errors.
This is my code:
import speech_recognition as voice
def voice_recognition():
speech = voice.Recognizer()
with voice.Microphone() as source:
print("SAY SOMETHING")
audio = speech.listen(source)
try:
command = speech.recognize_google(audio)
check = "forward" in command
check1 = "backward" in command
if(check == True):
print ('1')
if(check1 == True):
print ('2')
else:
print ('3')
except:
pass
voice_recognition()
And I am getting these errors:
Traceback (most recent call last):
File "/home/pi/Desktop/voice.py", line 29, in <module>
voice_recognition()
File "/home/pi/Desktop/voice.py", line 9, in voice_recognition
audio = speech.listen(source)
File "/usr/local/lib/python3.5/dist-packages/speech_recognition/__init__.py", line
620, in listen
buffer = source.stream.read(source.CHUNK)
File "/usr/local/lib/python3.5/dist-packages/speech_recognition/__init__.py", line
161, in read
return self.pyaudio_stream.read(size, exception_on_overflow=False)
File "/usr/local/lib/python3.5/dist-packages/pyaudio.py", line 608, in read
return pa.read_stream(self._stream, num_frames, exception_on_overflow)
The "errors" that you're seeing are normal when you terminate a Python program. If you run any Python code and terminate it (by pressing Ctrl+C on the command line) before it finishes, you will see a traceback of where the code terminated.
According to the speech_recognition library reference, Recognizer.listen() will not use a timeout by default (you can use listen(timeout=20) to timeout if nothing is received in 20 seconds). The code is probably using a wrong microphone, so the library never receives audio, so the program never terminates.
You should be able to use Microphone.list_microphone_names() to get a list of available microphones, and pass the index of your external microphone to the constructor (e.g. Microphone(device_index=3)).

Alsa Audio library - Error -> Has no PCM member

I'm working on a project where I have to control 8 audio channel.
I'm programming in python3 using alsaaudio library. It all worked but I have these 3 errors and, once I start the program, my internet connection goes down.
In the following code, you can see how I initialize the device (octosound card by AudioInjector). Please note that if the indentitation is wrong is just because a copy paste error.
import alsaaudio
def start_device(ch):
variables.mut.acquire()
if variables.device_flag[ch] == 1:
try:
variables.device_PCM[ch] = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode = alsaaudio.PCM_NORMAL,device=variables.device_name[ch])
variables.device_flag[ch] = 0 # device open
print('device -%s- OPEN' % (variables.device_name[ch]))
except:
print("Except raised")
json_builder.jsonerror("Init device ch" + str(ch) +" FAILED to OPEN",ch)
variables.device_flag[ch] == 1
else:
print("Device -%s- already opened" % (variables.device_name[ch]))
variables.mut.release()
The strange things are that this code works and I can drive all 8 channels but I got 3 errors and my internet stop working:
message: "Module 'alsaaudio' has no 'PCM' member"
message: "Module 'alsaaudio' has no 'PCM_PLAYBACK' member"
message: "Module 'alsaaudio' has no 'PCM_NORMAL' member"
(the device=device_name[ch] works, no error)
Well, I will recommend you to use Alvas.Audio Library which can edit, convert, play, pause convert audio files. The C# Alvas.Audio library can also be used to convert headerless format (SLINEAR) etc.
http://alvas.net/alvas.audio,tips.aspx
Moreover it helps to extract AVI streams and convert one file format to another. So, try the Alvas.Audio C# library and get free trial https://www.filerepairtools.com/alavas-audio-library.html

Categories

Resources