Display and play audio files - python

I am new to python, and I'm trying to build a simple recording program. With the some help from my previous question, I was able to add a timestamp for each recorded file
EDIT:
I did some research and decided on displaying the files with filechooser... this still does not work
def openfiles(self, *args):
satter2 = BoxLayout(pos= (629, 950), size_hint= (.1,.1))
self.fclv = FileChooserListView(path= '/sdcard/', filters= [‘*.3gp’])
self.fclv.bind(on_selection= self.pressed(fclv.selection)
scatter.add_widget(self.fclv)
self.add_widget(satter2)
def pressed(self, filename):
#with open(os.path.join(path, filename[0]))
if self.soundf is None:
self.soundf = SoundLoader.load(self.path)
if self.soundf.status != 'stop':
self.soundf.stop()
self.soundf.loop = False
self.soundf.play()

Here is a simple example of how to show all 3gp files in your current directory.
from kivy.app import App
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.boxlayout import BoxLayout
class MyLayout(BoxLayout):
def __init__(self,**kwargs):
super(MyLayout,self).__init__(**kwargs)
self.fclv = FileChooserListView(path= '.', filters= ['*.3gp'])
self.add_widget(self.fclv)
class MyApp(App):
def build(self):
return MyLayout()
MyApp().run()
Result is:

Related

using outter method inside a bind

I created a very simple GUI using Kivy which reads a CSV file and populates spinners with the data.
I would like once the spinner has been clicked, it will update the images that are beneath the spinner (using bind).
However, when I call the method updateImages it seems like nothing happens.
I looked at the following question and it seems like I did exactly the same however nothing happens.
How to get value outside function using python and kivy
Any help, please?
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
import pandas as pd
class GUI():
def loadData(self):
self.data = pd.read_csv('data.csv')
self.SValues = range(
min(self.data['sValue']), max(self.data['sValue']))
def updateImage(self, spinner, text):
for statue in self.SValues:
print(self.spinnerObject[statue])
try:
currLink = list(
self.data['Link'][self.data['Name'] == self.spinnerObject[statue].text])[0]
self.imageObject[statue] = Image(source=currLink)
self.imageObject[statue].size_hint = (
1/len(self.SValues), 0.1)
self.imageObject[statue].pos_hint = {
'x': (statue-1)/len(self.SValues), 'y': 0.6}
self.s_layout.add_widget(self.imageObject[statue])
except:
print('cant load image')
def initializeScreen(self):
self.spinnerObject = {}
self.imageObject = {}
self.s_layout = FloatLayout()
self.complete_layout = FloatLayout()
for statue in self.SValues:
self.spinnerObject[statue] = Spinner(text='sValue %d' % statue, values=list(
self.data['Name'][self.data['sValue'] == statue].values))
self.spinnerObject[statue].size_hint = (1/len(self.SValues), 0.1)
self.spinnerObject[statue].pos_hint = {
'x': (statue-1)/len(self.SValues), 'y': 0.7}
self.spinnerObject[statue].bind(text=self.updateImage)
self.s_layout.add_widget(self.spinnerObject[statue])
self.complete_layout.add_widget(self.s_layout)
return self.complete_layout
class MainApp(App):
def build(self):
gui = GUI()
gui.loadData()
layout = gui.initializeScreen()
return layout
if __name__ == '__main__':
MainApp().run()

Python Kivy: adding a FigureCanvas widget through a custom event

I am new to Kivy and GUIs in general and I am having a hard time understanding some simple concepts of Kivy callbacks logic. I want to make a simple app to read a CSV and plot a graph from it, so I want the widget that opens the file to trigger a function that adds a FigureCanvaKivyAgg widget that shows the figure.
On my source code I disabled the plotting from the CSV readed as it does not add to the issue at hand. You will see that I tried different ways to trigger the callback, but I only accomplish to trigger the custom event, it does not communicate with the callback nor add the FigureCanva Widget to the Layout.
import pandas as pd
import matplotlib.pyplot as plt
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserIconView
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from shark_plot import shark_plot
import os
csv = {'x':[1,2,3,4,5,6],'y':[2,4,6,8,6,12]}
class MyWidget(BoxLayout):
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
self.register_event_type('on_event')
container = BoxLayout(orientation='vertical')
filechooser = FileChooserIconView()
filechooser.bind(on_selection=lambda x: self.selected(filechooser.selection))
print(filechooser.selection,filechooser.path)
open_btn = Button(text='open', size_hint=(1, .2))
open_btn.bind(on_release=lambda x: self.open(filechooser.path, filechooser.selection))
box = BoxLayout(size_hint=(1, .5))
box.bind(on_event= self.action)
# if len(filechooser.path[0])>0:
# # box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
container.add_widget(filechooser)
container.add_widget(open_btn)
container.add_widget(box)
self.add_widget(container)
def on_event(self):
print("Event triggered?")
plt.show()
canva = (FigureCanvasKivyAgg(plt.gcf()))
return canva
def action(self):
print('Action executed??')
canva = (FigureCanvasKivyAgg(plt.gcf()))
self.cb.ask_update()
return canva
def open(self, path, filename):
print(filename)
if len(filename) > 0:
selected_path = os.path.join(path, filename[0])
print(selected_path)
df=pd.read_csv(selected_path)
# fig = shark_plot(df)
fig = plt.plot(csv['x'],csv['y'])
g=self.dispatch('on_event')
print(type(df))
# print(f.read())
return fig
def selected(self, filename):
print("selected: %s" % filename[0])
def on_event_callback():
print("Action Triggered??")
canva = (FigureCanvasKivyAgg(plt.gcf()))
subbox = BoxLayout()
subbox.add_widget(canva)
return subbox
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
Hope that the question is clear, it is my first time making such here :)
Please reach out for any clarifications.
on_event() will run via the dispatch() statement, but there is no connection from on_event() to the add_widget() statement in on_event_callback(), so that never happens. You can either put add_widget() directly in on_event(), or, if you want a separate function, then call it directly from open() without using the kivy register and dispatch().
def on_event(self):
canva = FigureCanvasKivyAgg(plt.gcf())
self.add_widget(canva)
def on_event_callback(self,canva):
self.add_widget(canva)
def open(self, path, filename):
# open data files here etc to load self.csv
plt.plot(self.csv['x'],self.csv['y'])
self.dispatch('on_event')
canva2 = FigureCanvasKivyAgg(plt.gcf())
self.on_event_callback(canva2)

Kivy stop Video and show photo

I'm working on a kivy framework (v1.10). I'm trying to create a simple photo booth software that runs a video loop and stops the video when someone clicks on the screen. After that the camera takes a picture and the program displays it on the monitor together with two buttons yes or no. they will allow you to repeat the photo. I am developing this application for Raspberry PI. My question is how do I stop the video and make something else.
ok, so if I want to add another movie between the first movie and the buttons, do I have to add a new screen or maybe change the video source in this funtion self.bind (on_touch_down = self.on_stop)? I would like to add a video with a countdown time and let him release the camera by taking pictures. then display this photo once with the buttons: repeat and continue.
from kivy.app import App
from kivy.logger import Logger
from kivy.uix.videoplayer import Video
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class Player(Video):
def __init__(self, **kwargs):
super(Player, self).__init__(**kwargs)
self.source = './START.mp4'
self.state='play'
self.options={'eos': 'loop'}
self.bind(on_touch_down = self.on_stop)
self.get_set_current_video_state = self.get_set_current_video_state()
def check(self):
Logger.info("film position:" + str(self.position))
def on_stop(self, *args):
print ('I have been clicked')
Player.state='stop'
#App.get_running_app().stop()
#self.get_set_current_video_state = ('pause')
return MyWindowApp().run()
class VideoPlayerApp(App):
def build(self):
return Player()
class MyWindowApp(App):
def __init__(self):
super(MyWindowApp, self).__init__()
self.btn = Button(text='Push Me!')
self.lbl = Label(text='Read Me!')
Instead of trying to use two Apps, just use two Screens. Here is a modification of your code using Screens:
from kivy.app import App
from kivy.logger import Logger
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.video import Video
from kivy.uix.label import Label
from kivy.uix.button import Button
class Player(Video):
def __init__(self, **kwargs):
super(Player, self).__init__(**kwargs)
self.source = './START.mp4'
self.state='play'
self.options={'eos': 'loop'}
self.bind(on_touch_down = self.on_stop)
def check(self):
Logger.info("film position:" + str(self.position))
def on_stop(self, *args):
print ('I have been clicked')
self.state='stop' # stop the video
sm.current = 'WindowApp' # switch to the other Screen
class MyWindowApp(Screen):
def __init__(self, **kwargs):
super(MyWindowApp, self).__init__(**kwargs)
self.btn = Button(text='Push Me!', pos_hint={'center_x': 0.5, 'center_y': 0.75}, size_hint=(0.2, 0.2))
self.lbl = Label(text='Read Me!', pos_hint={'center_x': 0.5, 'center_y': 0.25})
self.add_widget(self.btn)
self.add_widget(self.lbl)
sm = ScreenManager()
screen1 = Screen(name='video')
screen1.add_widget(Player())
sm.add_widget(screen1)
screen2 = MyWindowApp(name='WindowApp')
sm.add_widget(screen2)
class VideoPlayerApp(App):
def build(self):
return sm
VideoPlayerApp().run()
I corrected your import to from kivy.uix.video import Video

Kivy: issue with event defined variables

I am a complete noob on kivy (and object oriented approach in python programming) and I struggle trying to implement a simple file checker (I think I am missing a key element of kivy's logic). I want my app to indicate whether my file is a csv.
class CsvLoader(BoxLayout):
def __init__(self, **kwargs):
super(CsvLoader, self).__init__(**kwargs)
self.btn = Button(text='Please, Drag and Drop your CSV')
self.add_widget(self.btn)
csv = Window.bind(on_dropfile=self._on_file_drop) # this is the s*** part: how to get the file_path?
if str(csv).split('.')[-1] != "csv'" and csv != None:
self.clear_widgets()
btn_error = Button(text='Wrong file type')
self.add_widget(btn_error)
def _on_file_drop(self, window, file_path):
return file_path
class VisualizeMyCsv(App):
def build(self):
return CsvLoader()
if __name__ == '__main__':
VisualizeMyCsv().run()
What am I missing? Thanks
with the function bind you link an action, which in your case on_dropfile that triggers when you place a file, with a function that is called when the event is triggered, so the logic must be done within that method:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
class CsvLoader(BoxLayout):
def __init__(self, **kwargs):
super(CsvLoader, self).__init__(**kwargs)
self.btn = Button(text='Please, Drag and Drop your CSV')
self.add_widget(self.btn)
Window.bind(on_dropfile=self._on_file_drop)
def _on_file_drop(self, window, file_path):
if str(file_path).split('.')[-1] == "csv'":
print(file_path)
# here you must indicate that it is a .csv file
else:
# it is not a .csv file
print("it is not a .csv file")
class VisualizeMyCsv(App):
def build(self):
return CsvLoader()
if __name__ == '__main__':
VisualizeMyCsv().run()

Kivy - Parsing structure to widget

I'm having issues with parsing a data structure to a widget in Kivy, which would then access the structure and be able to show a value on the screen be updated continuously via a clock interval (not sure of a better to do this yet).
I have highlighted the issues in the (non-working) code below:
main.py
from kivy.app import App
from test import TestWidget
class TestApp(App):
def build(self):
testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}
# Issue here parsing the table like this?
return TestWidget(testStructTable)
if __name__ == '__main__':
TestApp().run()
test.py
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty
class TestWidget(RelativeLayout):
def __init__(self, testStructTable, **kwargs):
super(TestWidget, self).__init__(**kwargs)
Builder.load_file('test.kv')
sm = ScreenManager()
sm.add_widget(MainScreen(name='MainScreen'))
self.add_widget(sm)
# Error accessing the table
print self.testStructTable
# Have the update_test_val continuously called
#Clock.schedule_interval(MainScreen.update_test_val(testStructTable), 1 / 60)
class MainScreen(Screen):
def __init__(self, **kwargs):
testVal = NumericProperty(0)
def update_test_val(self, testStructTable):
# Get testVal from testStructTable
# Something like:
# self.testVal = testStructTable.testVal + 1 ?
self.testVal = self.testVal + 1
test.kv
<MainScreen>:
FloatLayout:
Label:
text: str(root.testVal)
font_size: 80
My aim is to have the testVal constantly updating on the screen by accessing that data structure, however I am currently unable to achieve this, can you please advise?
In your __init__ method you're passing testStructTable and then you're trying to access self.testStructTable which does not exist untill you explicitly make an assignment:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty
class TestWidget(RelativeLayout):
def __init__(self, testStructTable, **kwargs):
super(TestWidget, self).__init__(**kwargs)
print(testStructTable)
self.testStructTable = testStructTable
print(self.testStructTable)
class TestApp(App):
def build(self):
testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}
# Issue here parsing the table like this?
return TestWidget(testStructTable)
if __name__ == '__main__':
TestApp().run()

Categories