From 9f2a9aba3aff73e31ea15eb4a7a04b0e50f4ee4e Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Fri, 5 Jan 2018 15:58:35 +0100 Subject: Move examples from submodule to pyside-setup Move PySide2 examples that are owned by the Qt Company to a new examples directory. Done-with: Venugopal Shivashankar Task-number: PYSIDE-363 Change-Id: I14099764d9eef2bc35e067086121427955862e3a Reviewed-by: Alexandru Croitor --- examples/multimedia/audiooutput.py | 301 +++++++++++++++++++++++++++++++++++++ examples/multimedia/camera.py | 170 +++++++++++++++++++++ examples/multimedia/player.py | 158 +++++++++++++++++++ 3 files changed, 629 insertions(+) create mode 100755 examples/multimedia/audiooutput.py create mode 100644 examples/multimedia/camera.py create mode 100644 examples/multimedia/player.py (limited to 'examples/multimedia') diff --git a/examples/multimedia/audiooutput.py b/examples/multimedia/audiooutput.py new file mode 100755 index 000000000..270683110 --- /dev/null +++ b/examples/multimedia/audiooutput.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python + +############################################################################# +## +## Copyright (C) 2013 Riverbank Computing Limited. +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: http://www.qt.io/licensing/ +## +## This file is part of the PySide examples of the Qt Toolkit. +## +## $QT_BEGIN_LICENSE:BSD$ +## You may use this file under the terms of the BSD license as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################# + +"""PySide2 port of the multimedia/audiooutput example from Qt v5.x, originating from PyQt""" + +from math import pi, sin +from struct import pack + +from PySide2.QtCore import QByteArray, QIODevice, Qt, QTimer, qWarning +from PySide2.QtMultimedia import (QAudio, QAudioDeviceInfo, QAudioFormat, + QAudioOutput) +from PySide2.QtWidgets import (QApplication, QComboBox, QHBoxLayout, QLabel, + QMainWindow, QPushButton, QSlider, QVBoxLayout, QWidget) + + +class Generator(QIODevice): + + def __init__(self, format, durationUs, sampleRate, parent): + super(Generator, self).__init__(parent) + + self.m_pos = 0 + self.m_buffer = QByteArray() + + self.generateData(format, durationUs, sampleRate) + + def start(self): + self.open(QIODevice.ReadOnly) + + def stop(self): + self.m_pos = 0 + self.close() + + def generateData(self, format, durationUs, sampleRate): + pack_format = '' + + if format.sampleSize() == 8: + if format.sampleType() == QAudioFormat.UnSignedInt: + scaler = lambda x: ((1.0 + x) / 2 * 255) + pack_format = 'B' + elif format.sampleType() == QAudioFormat.SignedInt: + scaler = lambda x: x * 127 + pack_format = 'b' + elif format.sampleSize() == 16: + if format.sampleType() == QAudioFormat.UnSignedInt: + scaler = lambda x: (1.0 + x) / 2 * 65535 + pack_format = 'H' + elif format.sampleType() == QAudioFormat.SignedInt: + scaler = lambda x: x * 32767 + pack_format = 'h' + + assert(pack_format != '') + + channelBytes = format.sampleSize() // 8 + sampleBytes = format.channelCount() * channelBytes + + length = (format.sampleRate() * format.channelCount() * (format.sampleSize() // 8)) * durationUs // 100000 + + self.m_buffer.clear() + sampleIndex = 0 + factor = 2 * pi * sampleRate / format.sampleRate() + + while length != 0: + x = sin((sampleIndex % format.sampleRate()) * factor) + packed = pack(pack_format, int(scaler(x))) + + for _ in range(format.channelCount()): + self.m_buffer.append(packed) + length -= channelBytes + + sampleIndex += 1 + + def readData(self, maxlen): + data = QByteArray() + total = 0 + + while maxlen > total: + chunk = min(self.m_buffer.size() - self.m_pos, maxlen - total) + data.append(self.m_buffer.mid(self.m_pos, chunk)) + self.m_pos = (self.m_pos + chunk) % self.m_buffer.size() + total += chunk + + return data.data() + + def writeData(self, data): + return 0 + + def bytesAvailable(self): + return self.m_buffer.size() + super(Generator, self).bytesAvailable() + + +class AudioTest(QMainWindow): + + PUSH_MODE_LABEL = "Enable push mode" + PULL_MODE_LABEL = "Enable pull mode" + SUSPEND_LABEL = "Suspend playback" + RESUME_LABEL = "Resume playback" + + DurationSeconds = 1 + ToneSampleRateHz = 600 + DataSampleRateHz = 44100 + + def __init__(self): + super(AudioTest, self).__init__() + + self.m_device = QAudioDeviceInfo.defaultOutputDevice() + self.m_output = None + + self.initializeWindow() + self.initializeAudio() + + def initializeWindow(self): + layout = QVBoxLayout() + + self.m_deviceBox = QComboBox() + self.m_deviceBox.activated[int].connect(self.deviceChanged) + for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput): + self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo) + + layout.addWidget(self.m_deviceBox) + + self.m_modeButton = QPushButton() + self.m_modeButton.clicked.connect(self.toggleMode) + self.m_modeButton.setText(self.PUSH_MODE_LABEL) + + layout.addWidget(self.m_modeButton) + + self.m_suspendResumeButton = QPushButton( + clicked=self.toggleSuspendResume) + self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) + + layout.addWidget(self.m_suspendResumeButton) + + volumeBox = QHBoxLayout() + volumeLabel = QLabel("Volume:") + self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100, + singleStep=10) + self.m_volumeSlider.valueChanged.connect(self.volumeChanged) + + volumeBox.addWidget(volumeLabel) + volumeBox.addWidget(self.m_volumeSlider) + + layout.addLayout(volumeBox) + + window = QWidget() + window.setLayout(layout) + + self.setCentralWidget(window) + + def initializeAudio(self): + self.m_pullTimer = QTimer(self) + self.m_pullTimer.timeout.connect(self.pullTimerExpired) + self.m_pullMode = True + + self.m_format = QAudioFormat() + self.m_format.setSampleRate(self.DataSampleRateHz) + self.m_format.setChannelCount(1) + self.m_format.setSampleSize(16) + self.m_format.setCodec('audio/pcm') + self.m_format.setByteOrder(QAudioFormat.LittleEndian) + self.m_format.setSampleType(QAudioFormat.SignedInt) + + info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice()) + if not info.isFormatSupported(self.m_format): + qWarning("Default format not supported - trying to use nearest") + self.m_format = info.nearestFormat(self.m_format) + + self.m_generator = Generator(self.m_format, + self.DurationSeconds * 1000000, self.ToneSampleRateHz, self) + + self.createAudioOutput() + + def createAudioOutput(self): + self.m_audioOutput = QAudioOutput(self.m_device, self.m_format) + self.m_audioOutput.notify.connect(self.notified) + self.m_audioOutput.stateChanged.connect(self.handleStateChanged) + + self.m_generator.start() + self.m_audioOutput.start(self.m_generator) + self.m_volumeSlider.setValue(self.m_audioOutput.volume() * 100) + + def deviceChanged(self, index): + self.m_pullTimer.stop() + self.m_generator.stop() + self.m_audioOutput.stop() + self.m_device = self.m_deviceBox.itemData(index) + + self.createAudioOutput() + + def volumeChanged(self, value): + if self.m_audioOutput is not None: + self.m_audioOutput.setVolume(value / 100.0) + + def notified(self): + qWarning("bytesFree = %d, elapsedUSecs = %d, processedUSecs = %d" % ( + self.m_audioOutput.bytesFree(), + self.m_audioOutput.elapsedUSecs(), + self.m_audioOutput.processedUSecs())) + + def pullTimerExpired(self): + if self.m_audioOutput is not None and self.m_audioOutput.state() != QAudio.StoppedState: + chunks = self.m_audioOutput.bytesFree() // self.m_audioOutput.periodSize() + for _ in range(chunks): + data = self.m_generator.read(self.m_audioOutput.periodSize()) + if data is None or len(data) != self.m_audioOutput.periodSize(): + break + + self.m_output.write(data) + + def toggleMode(self): + self.m_pullTimer.stop() + self.m_audioOutput.stop() + + if self.m_pullMode: + self.m_modeButton.setText(self.PULL_MODE_LABEL) + self.m_output = self.m_audioOutput.start() + self.m_pullMode = False + self.m_pullTimer.start(20) + else: + self.m_modeButton.setText(self.PUSH_MODE_LABEL) + self.m_pullMode = True + self.m_audioOutput.start(self.m_generator) + + self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) + + def toggleSuspendResume(self): + if self.m_audioOutput.state() == QAudio.SuspendedState: + qWarning("status: Suspended, resume()") + self.m_audioOutput.resume() + self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) + elif self.m_audioOutput.state() == QAudio.ActiveState: + qWarning("status: Active, suspend()") + self.m_audioOutput.suspend() + self.m_suspendResumeButton.setText(self.RESUME_LABEL) + elif self.m_audioOutput.state() == QAudio.StoppedState: + qWarning("status: Stopped, resume()") + self.m_audioOutput.resume() + self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) + elif self.m_audioOutput.state() == QAudio.IdleState: + qWarning("status: IdleState") + + stateMap = { + QAudio.ActiveState: "ActiveState", + QAudio.SuspendedState: "SuspendedState", + QAudio.StoppedState: "StoppedState", + QAudio.IdleState: "IdleState"} + + def handleStateChanged(self, state): + qWarning("state = " + self.stateMap.get(state, "Unknown")) + + +if __name__ == '__main__': + + import sys + + app = QApplication(sys.argv) + app.setApplicationName("Audio Output Test") + + audio = AudioTest() + audio.show() + + sys.exit(app.exec_()) diff --git a/examples/multimedia/camera.py b/examples/multimedia/camera.py new file mode 100644 index 000000000..1b8d5ad47 --- /dev/null +++ b/examples/multimedia/camera.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python + +############################################################################# +## +## Copyright (C) 2017 The Qt Company Ltd. +## Contact: http://www.qt.io/licensing/ +## +## This file is part of the PySide examples of the Qt Toolkit. +## +## $QT_BEGIN_LICENSE:BSD$ +## You may use this file under the terms of the BSD license as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################# + +"""PySide2 Multimedia Camera Example""" + +import os, sys +from PySide2.QtCore import QDate, QDir, QStandardPaths, Qt, QUrl +from PySide2.QtGui import QClipboard, QGuiApplication, QDesktopServices, QIcon +from PySide2.QtGui import QImage, QPixmap +from PySide2.QtWidgets import (QAction, qApp, QApplication, QHBoxLayout, QLabel, + QMainWindow, QPushButton, QTabWidget, QToolBar, QVBoxLayout, QWidget) +from PySide2.QtMultimedia import QCamera, QCameraImageCapture, QCameraInfo +from PySide2.QtMultimediaWidgets import QCameraViewfinder + +class ImageView(QWidget): + def __init__(self, previewImage, fileName): + super(ImageView, self).__init__() + + self.fileName = fileName + + mainLayout = QVBoxLayout(self) + self.imageLabel = QLabel() + self.imageLabel.setPixmap(QPixmap.fromImage(previewImage)) + mainLayout.addWidget(self.imageLabel) + + topLayout = QHBoxLayout() + self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName)) + self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction) + + topLayout.addWidget(self.fileNameLabel) + topLayout.addStretch() + copyButton = QPushButton("Copy") + copyButton.setToolTip("Copy file name to clipboard") + topLayout.addWidget(copyButton) + copyButton.clicked.connect(self.copy) + launchButton = QPushButton("Launch") + launchButton.setToolTip("Launch image viewer") + topLayout.addWidget(launchButton) + launchButton.clicked.connect(self.launch) + mainLayout.addLayout(topLayout) + + def copy(self): + QGuiApplication.clipboard().setText(self.fileNameLabel.text()) + + def launch(self): + QDesktopServices.openUrl(QUrl.fromLocalFile(self.fileName)) + +class MainWindow(QMainWindow): + def __init__(self): + super(MainWindow, self).__init__() + + self.cameraInfo = QCameraInfo.defaultCamera() + self.camera = QCamera(self.cameraInfo) + self.camera.setCaptureMode(QCamera.CaptureStillImage) + self.imageCapture = QCameraImageCapture(self.camera) + self.imageCapture.imageCaptured.connect(self.imageCaptured) + self.imageCapture.imageSaved.connect(self.imageSaved) + self.currentPreview = QImage() + + toolBar = QToolBar() + self.addToolBar(toolBar) + + fileMenu = self.menuBar().addMenu("&File") + shutterIcon = QIcon(os.path.join(os.path.dirname(__file__), + "shutter.svg")) + self.takePictureAction = QAction(shutterIcon, "&Take Picture", self, + shortcut="Ctrl+T", + triggered=self.takePicture) + self.takePictureAction.setToolTip("Take Picture") + fileMenu.addAction(self.takePictureAction) + toolBar.addAction(self.takePictureAction) + + exitAction = QAction(QIcon.fromTheme("application-exit"), "E&xit", + self, shortcut="Ctrl+Q", triggered=self.close) + fileMenu.addAction(exitAction) + + aboutMenu = self.menuBar().addMenu("&About") + aboutQtAction = QAction("About &Qt", self, triggered=qApp.aboutQt) + aboutMenu.addAction(aboutQtAction) + + self.tabWidget = QTabWidget() + self.setCentralWidget(self.tabWidget) + + self.cameraViewfinder = QCameraViewfinder() + self.camera.setViewfinder(self.cameraViewfinder) + self.tabWidget.addTab(self.cameraViewfinder, "Viewfinder") + + if self.camera.status() != QCamera.UnavailableStatus: + name = self.cameraInfo.description() + self.setWindowTitle("PySide2 Camera Example (" + name + ")") + self.statusBar().showMessage("Starting: '" + name + "'", 5000) + self.camera.start() + else: + self.setWindowTitle("PySide2 Camera Example") + self.takePictureAction.setEnabled(False) + self.statusBar().showMessage("Camera unavailable", 5000) + + def nextImageFileName(self): + picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) + dateString = QDate.currentDate().toString("yyyyMMdd") + pattern = picturesLocation + "/pyside2_camera_" + dateString + "_{:03d}.jpg" + n = 1 + while True: + result = pattern.format(n) + if not os.path.exists(result): + return result + n = n + 1 + return None + + def takePicture(self): + self.currentPreview = QImage() + self.camera.searchAndLock() + self.imageCapture.capture(self.nextImageFileName()) + self.camera.unlock() + + def imageCaptured(self, id, previewImage): + self.currentPreview = previewImage + + def imageSaved(self, id, fileName): + index = self.tabWidget.count() + imageView = ImageView(self.currentPreview, fileName) + self.tabWidget.addTab(imageView, "Capture #{}".format(index)) + self.tabWidget.setCurrentIndex(index) + +if __name__ == '__main__': + app = QApplication(sys.argv) + mainWin = MainWindow() + availableGeometry = app.desktop().availableGeometry(mainWin) + mainWin.resize(availableGeometry.width() / 3, availableGeometry.height() / 2) + mainWin.show() + sys.exit(app.exec_()) diff --git a/examples/multimedia/player.py b/examples/multimedia/player.py new file mode 100644 index 000000000..76445cd30 --- /dev/null +++ b/examples/multimedia/player.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python + +############################################################################# +## +## Copyright (C) 2017 The Qt Company Ltd. +## Contact: http://www.qt.io/licensing/ +## +## This file is part of the PySide examples of the Qt Toolkit. +## +## $QT_BEGIN_LICENSE:BSD$ +## You may use this file under the terms of the BSD license as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################# + +"""PySide2 Multimedia player example""" + +import sys +from PySide2.QtCore import SLOT, QStandardPaths, Qt +from PySide2.QtGui import QIcon, QKeySequence +from PySide2.QtWidgets import (QAction, qApp, QApplication, QDialog, QFileDialog, + QMainWindow, QMenu, QMenuBar, QSlider, QStyle, QToolBar) +from PySide2.QtMultimedia import QMediaPlayer, QMediaPlaylist +from PySide2.QtMultimediaWidgets import QVideoWidget + +class MainWindow(QMainWindow): + + def __init__(self): + super(MainWindow, self).__init__() + + self.playlist = QMediaPlaylist() + self.player = QMediaPlayer() + + toolBar = QToolBar() + self.addToolBar(toolBar) + + fileMenu = self.menuBar().addMenu("&File") + openAction = QAction(QIcon.fromTheme("document-open"), + "&Open...", self, shortcut=QKeySequence.Open, + triggered=self.open) + fileMenu.addAction(openAction) + exitAction = QAction(QIcon.fromTheme("application-exit"), "E&xit", + self, shortcut="Ctrl+Q", triggered=self.close) + fileMenu.addAction(exitAction) + + playMenu = self.menuBar().addMenu("&Play") + playIcon = self.style().standardIcon(QStyle.SP_MediaPlay) + self.playAction = toolBar.addAction(playIcon, "Play") + self.playAction.triggered.connect(self.player.play) + playMenu.addAction(self.playAction) + + previousIcon = self.style().standardIcon(QStyle.SP_MediaSkipBackward) + self.previousAction = toolBar.addAction(previousIcon, "Previous") + self.previousAction.triggered.connect(self.previousClicked) + playMenu.addAction(self.previousAction) + + pauseIcon = self.style().standardIcon(QStyle.SP_MediaPause) + self.pauseAction = toolBar.addAction(pauseIcon, "Pause") + self.pauseAction.triggered.connect(self.player.pause) + playMenu.addAction(self.pauseAction) + + nextIcon = self.style().standardIcon(QStyle.SP_MediaSkipForward) + self.nextAction = toolBar.addAction(nextIcon, "Next") + self.nextAction.triggered.connect(self.playlist.next) + playMenu.addAction(self.nextAction) + + stopIcon = self.style().standardIcon(QStyle.SP_MediaStop) + self.stopAction = toolBar.addAction(stopIcon, "Stop") + self.stopAction.triggered.connect(self.player.stop) + playMenu.addAction(self.stopAction) + + self.volumeSlider = QSlider() + self.volumeSlider.setOrientation(Qt.Horizontal) + self.volumeSlider.setMinimum(0) + self.volumeSlider.setMaximum(100) + self.volumeSlider.setFixedWidth(app.desktop().availableGeometry(self).width() / 10) + self.volumeSlider.setValue(self.player.volume()) + self.volumeSlider.setTickInterval(10) + self.volumeSlider.setTickPosition(QSlider.TicksBelow) + self.volumeSlider.setToolTip("Volume") + self.volumeSlider.valueChanged.connect(self.player.setVolume) + toolBar.addWidget(self.volumeSlider) + + aboutMenu = self.menuBar().addMenu("&About") + aboutQtAct = QAction("About &Qt", self, triggered=qApp.aboutQt) + aboutMenu.addAction(aboutQtAct) + + self.videoWidget = QVideoWidget() + self.setCentralWidget(self.videoWidget) + self.player.setPlaylist(self.playlist); + self.player.stateChanged.connect(self.updateButtons) + self.player.setVideoOutput(self.videoWidget); + + self.updateButtons(self.player.state()) + + def open(self): + fileDialog = QFileDialog(self) + supportedMimeTypes = QMediaPlayer.supportedMimeTypes() + if not supportedMimeTypes: + supportedMimeTypes.append("video/x-msvideo") # AVI + fileDialog.setMimeTypeFilters(supportedMimeTypes) + moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation) + fileDialog.setDirectory(moviesLocation) + if fileDialog.exec_() == QDialog.Accepted: + self.playlist.addMedia(fileDialog.selectedUrls()[0]) + self.player.play() + + def previousClicked(self): + # Go to previous track if we are within the first 5 seconds of playback + # Otherwise, seek to the beginning. + if self.player.position() <= 5000: + self.playlist.previous(); + else: + player.setPosition(0); + + def updateButtons(self, state): + mediaCount = self.playlist.mediaCount() + self.playAction.setEnabled(mediaCount > 0 + and state != QMediaPlayer.PlayingState) + self.pauseAction.setEnabled(state == QMediaPlayer.PlayingState) + self.stopAction.setEnabled(state != QMediaPlayer.StoppedState) + self.previousAction.setEnabled(self.player.position() > 0) + self.nextAction.setEnabled(mediaCount > 1) + +if __name__ == '__main__': + app = QApplication(sys.argv) + mainWin = MainWindow() + availableGeometry = app.desktop().availableGeometry(mainWin) + mainWin.resize(availableGeometry.width() / 3, availableGeometry.height() / 2) + mainWin.show() + sys.exit(app.exec_()) -- cgit v1.2.3