-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMediaPlayer.py
454 lines (366 loc) · 17.5 KB
/
MediaPlayer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
from PyQt5.QtCore import QDir, Qt, QUrl, QThread, QRunnable, QThreadPool, QTimer
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
from PyQt5.QtWidgets import QMainWindow,QWidget, QPushButton, QAction, QGridLayout, QLineEdit, QMessageBox
from PyQt5.QtGui import QIcon,QFont
import sys
import threading
import time
import json
import Form
import math
from os import listdir
from pynput.mouse import Controller
import MultiLanguage
class MediaPlayer(QMainWindow):
def __init__(self, parent=None, questions = None, time = None, answered_form = None):
# Initalize self and variables
super(MediaPlayer, self).__init__(parent)
self.parent = parent
self.questions = questions
self.answered_form = answered_form
self.time = time
self.setWindowTitle("Dynamic State Tracker " + parent.version)
# Reset data in questions!
for q in self.questions:
q.reset_data()
# Controller component is needed to track mouse while it is not clicked.
self.mouse = Controller()
# The player should be maximised! This is due to how the mouse tracking works.
self.showMaximized()
# Create media player and video widget.
self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
videoWidget = QVideoWidget()
# create play button
self.playButton = QPushButton()
self.playButton.setEnabled(False)
self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.playButton.clicked.connect(self.play)
# Create slider for video position
self.positionSlider = QSlider(Qt.Horizontal)
self.positionSlider.setStyleSheet("QSlider::handle:horizontal {background-color: grey; border: 1px solid #777; width 13px; margin-top: -3px; margin-bottom: -3px; border-radius: 2px;}")
self.positionSlider.setRange(0, 0)
self.positionSlider.sliderMoved.connect(self.setPosition)
# Create label for video position
self.positionLabel = QLabel("0")
newfont = QFont("Times", 20)
self.positionLabel.setFont(newfont)
# Create label to output errors
self.errorLabel = QLabel()
self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
QSizePolicy.Maximum)
# Create new action
openAction = QAction(QIcon('open.png'), self.parent.MultiLang.find_correct_word("Open"), self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open movie')
openAction.triggered.connect(self.openFile)
# Create exit action
exitAction = QAction(QIcon('exit.png'), self.parent.MultiLang.find_correct_word("Exit"), self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.exitCall)
# Create save action
saveAction = QAction(QIcon('save.png'), self.parent.MultiLang.find_correct_word("Save"), self)
saveAction.setShortcut('Ctrl+S')
saveAction.triggered.connect(self.saveAndExit)
# Create menu bar and add action
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(openAction)
fileMenu.addAction(exitAction)
fileMenu.addAction(saveAction)
# Create a widget for window contents
wid = QWidget(self)
self.setCentralWidget(wid)
# Create layouts to place inside widget
controlLayout = QHBoxLayout()
controlLayout.setContentsMargins(0, 0, 0, 0)
controlLayout.addWidget(self.playButton)
controlLayout.addWidget(self.positionSlider)
controlLayout.addWidget(self.positionLabel)
self.layout = QGridLayout()
self.layout.setRowStretch(0,2)
self.layout.setVerticalSpacing(1)
self.layout.addWidget(videoWidget,0,0)
self.layout.addLayout(controlLayout,1,0)
# Set widget to contain window contents
wid.setLayout(self.layout)
self.mediaPlayer.setVideoOutput(videoWidget)
self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
self.mediaPlayer.positionChanged.connect(self.positionChanged)
self.mediaPlayer.durationChanged.connect(self.durationChanged)
self.mediaPlayer.error.connect(self.handleError)
## ADD INPUT METHOD DEPENDING ON AMOUNT OF QUESTIONS AND TIME
if(len(self.questions) == 1):
self.create_single_mode()
elif(len(self.questions) > 1):
# Initalize type variable for later.
self.type = "multi"
#Add timer
self.timer = QTimer()
self.timer.timeout.connect(self.record)
#For mouse smoothness
self.auto_mouse_timer = QTimer()
self.auto_mouse_timer.timeout.connect(self.update_mouse)
# Add error label to layout
self.layout.addWidget(self.errorLabel)
def create_single_mode(self):
'''
This function is called when the program is in single question mode.
It creates the slider, question and labels.
It also sets type to 'one' (this is used later for recording)
'''
# Initalize slider, initalize type variable for later.
self.percent_text = QLabel("0")
self.slider = QSlider(Qt.Horizontal)
self.slider.setStyleSheet("QSlider::handle:horizontal {background-color: blue; border: 1px solid #777; width 13px; margin-top: -2px; margin-bottom: -2px; border-radius: 4px;}")
self.slider.setFocusPolicy(Qt.StrongFocus)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.setTickInterval(10)
self.slider.setSingleStep(1)
self.slider.valueChanged.connect(self.value_change)
self.slider.setMouseTracking(True)
self.type = "one"
# Creates a label with the asked question, then adds it to the main layout.
self.question_text = QLabel(self.questions[0].get_question())
newfont = QFont("Times", 20, QFont.Bold)
self.question_text.setFont(newfont)
self.layout.addWidget(self.question_text,3,0, Qt.AlignCenter)
# Labels for the extremes
max_label = QLabel(self.questions[0].get_max())
min_label = QLabel(self.questions[0].get_min())
newfont = QFont("Times", 16, QFont.Bold)
max_label.setFont(newfont)
min_label.setFont(newfont)
textLayout = QHBoxLayout()
textLayout.setContentsMargins(0, 0, 0 ,0)
textLayout.addWidget(min_label,0, Qt.AlignLeft)
textLayout.addWidget(max_label,0, Qt.AlignRight)
self.layout.addLayout(textLayout, 5, 0)
# Create layouts to place slider inside
sliderLayout = QHBoxLayout()
sliderLayout.setContentsMargins(0, 0, 0, 0)
# Add slider and percent text to slider layout.
sliderLayout.addWidget(self.slider)
sliderLayout.addWidget(self.percent_text)
# Add slider layout to the main window layout.
self.layout.addLayout(sliderLayout,4,0)
def closeEvent(self, event):
print ("Closing")
if self.timer.isActive():
self.timer.stop()
if self.auto_mouse_timer.isActive():
self.auto_mouse_timer.stop()
#self.close()
def value_change(self):
size = str(self.slider.value())
self.percent_text.setText(size)
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, self.parent.MultiLang.find_correct_word("Open Movie"),
QDir.homePath())
if fileName != '':
print ("Loading url: " + fileName)
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
print ("Loading Qurl: " + str(QUrl.fromLocalFile(fileName)))
self.playButton.setEnabled(True)
self.video_dir = fileName
def exitCall(self):
print("Exiting!")
self.close()
def play(self):
if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
self.mediaPlayer.pause()
else:
self.mediaPlayer.play()
def mediaStateChanged(self, state):
'''
If media state is changed, this function is called.
If the video is playing, the timer is started for recording input.
If the video is paused, the timer is stopped.
If the video is ended, open the save window and end the timer.
'''
if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
# set timer interval to self.time. This self.time is loaded from the setQuestions settings.
self.timer.start(self.time)
self.auto_mouse_timer.start(50)
elif self.mediaPlayer.state() == QMediaPlayer.StoppedState:
self.saveAndExit()
else:
self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.timer.stop()
self.auto_mouse_timer.stop
def positionChanged(self, position):
self.positionSlider.setValue(position)
self.positionLabel.setText(self.format_time(self.mediaPlayer.position()))
def format_time(self, m_seconds):
'''
Format time from milli seconds to (mins:seconds).
'''
seconds = round(m_seconds/1000)
mins = math.floor(seconds / 60)
reduced_seconds = seconds % 60
# Add 0 before second digit if it is less than 10.
if (reduced_seconds < 10):
seconds_str = "0" + str(reduced_seconds)
else:
seconds_str = str(reduced_seconds)
formated_time = str(mins) + ":" + seconds_str
return formated_time
def durationChanged(self, duration):
self.positionSlider.setRange(0, duration)
def setPosition(self, position):
self.mediaPlayer.setPosition(position)
def handleError(self):
self.playButton.setEnabled(False)
self.errorLabel.setText("Error: " + self.mediaPlayer.errorString())
def update_mouse(self):
'''
Updates the position of slider based on the position of mouse across the window.
'''
if self.type == "one":
size_x = self.slider.geometry().width()
new_value = int(100*self.mouse.position[0]/size_x)
self.slider.setValue(new_value)
def record(self):
'''
This function performs the recording of input. If we are in single question mode, first the slider will update to the mouse, and then it will be recorded.
If in multi-question mode, the 'MultiQuestionPopUP' class is used to record the input.
'''
if self.type == "one":
size_x = self.slider.geometry().width()
new_value = int(100*self.mouse.position[0]/size_x)
self.slider.setValue(new_value)
self.questions[0].add_data(new_value)
elif self.type == "multi":
self.timer.stop()
popup = MultiQuestionPopUP(self)
self.play() #Actually pauses, confusingly
def saveAndExit(self):
if(self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.play() #Actually pauses.
self.timer.stop()
save_window = SaveFileWindow(self)
class MultiQuestionPopUP(QMainWindow):
def __init__(self, parent=None):
super(MultiQuestionPopUP, self).__init__(parent)
self.setWindowTitle(parent.parent.MultiLang.find_correct_word("Questions"))
self.parent = parent
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
# A list to hold all the sliders so we can reference back to them later on submit!
self.slider_list= list()
self.create_question_segments()
self.submit_button = QPushButton("Submit")
self.submit_button.clicked.connect(self.submit)
self.layout.addWidget(self.submit_button, len(self.slider_list)*2, 0) # the position here is multiplied by 2 because each question has a label and slider.
self.show()
def create_question_segments(self):
'''
Creates all the sliders and questions in the multi-question pop up.
'''
index = 0
for q in self.parent.questions:
question = QLabel(q.get_question())
slider = QSlider(Qt.Horizontal)
slider.setFocusPolicy(Qt.StrongFocus)
slider.setTickPosition(QSlider.TicksBothSides)
slider.setTickInterval(10)
slider.setSingleStep(1)
slider.setMouseTracking(True)
self.slider_list.append(slider)
last_value = q.last_value()
if (last_value != None):
slider.setValue(last_value)
min_label = QLabel(q.get_min())
max_label = QLabel(q.get_max())
self.layout.addWidget(question,index,1)
self.layout.addWidget(slider, index+1, 1)
self.layout.addWidget(min_label, index+1, 0)
self.layout.addWidget(max_label, index+1, 2)
index = index + 2
def submit(self):
'''
Adds data to all the questions when user submits the multi-question window.
Then restart the player and close this instance of multi-window.
'''
i = 0
for q in self.parent.questions:
q.add_data(self.slider_list[i].value())
i = i + 1
self.parent.play() #Restarts player
self.close()
class SaveFileWindow(QMainWindow):
def __init__(self, parent=None):
super(SaveFileWindow, self).__init__(parent)
self.setWindowTitle(parent.parent.MultiLang.find_correct_word("Save file as:"))
self.parent = parent
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
self.file_name_box = QLineEdit( self.parent.parent.MultiLang.find_correct_word("File name here"))
self.layout.addWidget(self.file_name_box, 0, 0)
self.save_button = QPushButton( self.parent.parent.MultiLang.find_correct_word("Save file"))
self.save_button.clicked.connect(self.save_file)
self.layout.addWidget(self.save_button, 0, 1)
self.show()
def save_file(self):
'''
Attempts to save file with the name in the text box.
Saves both questions and form.
'''
file_name = self.file_name_box.text()
# If there is no filename, then do nothing.
if (file_name == ""):
return
for name in listdir("saves/"):
if name == (file_name + ".txt") :
buttonReply = QMessageBox.question(self, 'Attempted Overwrite', self.parent.parent.MultiLang.find_correct_word("Are you sure you want to overwrite") + " [" + file_name + "]", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if buttonReply == QMessageBox.No:
return
try:
f = open("saves/" + file_name + ".txt", "w+")
f.write(self.parent.video_dir + "//")
f.write(str(self.parent.time) + "//")
for q in self.parent.questions:
save_string = q.get_question() + "|" + q.get_min() + "|" + q.get_max() + " - " + json.dumps(q.get_data())
f.write(save_string + "//")
# This is the symbol that splits the object.
f.write("~")
for q in self.parent.answered_form:
first_text = str(q.get_question())
second_text = str(q.get_data())
save_string = first_text + " - " + second_text
f.write(save_string + "//")
f.close()
print("Sucessfully saved!")
except:
print("Saving failed!")
exit_window = EndWindow(self, self.parent.parent.MultiLang.find_correct_word("Thank you and goodbye!"))
class EndWindow(QMainWindow):
def __init__(self, parent = None, text = None):
super(EndWindow, self).__init__(parent)
self.setWindowTitle(parent.parent.parent.MultiLang.find_correct_word("Exit window"))
self.parent = parent
self.layout = QGridLayout()
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
self.main_widget.setLayout(self.layout)
self.label = QLabel(text)
self.accept_button = QPushButton(self.parent.parent.parent.MultiLang.find_correct_word("Finish"))
self.accept_button.clicked.connect(self.accept)
self.layout.addWidget(self.label, 0, 0)
self.layout.addWidget(self.accept_button, 1, 0)
self.show()
def accept(self):
'''
Close video player, close save window, close self.
'''
self.parent.parent.close()
self.parent.close()
self.close()