Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmediaplayer.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include <private/qmultimediautils_p.h>
7#include <private/qplatformmediaintegration_p.h>
8#include <private/qaudiobufferoutput_p.h>
9#include <qvideosink.h>
10#include <qaudiooutput.h>
11
12#include <QtCore/qcoreevent.h>
13#include <QtCore/qmetaobject.h>
14#include <QtCore/qtimer.h>
15#include <QtCore/qdebug.h>
16#include <QtCore/qdir.h>
17#include <QtCore/qpointer.h>
18#include <QtCore/qfileinfo.h>
19#include <QtCore/qtemporaryfile.h>
20#include <QtCore/qcoreapplication.h>
21
22#if defined(Q_OS_ANDROID)
23# include <QtCore/qjniobject.h>
24#endif
25
27
28/*!
29 \class QMediaPlayer
30 \brief The QMediaPlayer class allows the playing of a media files.
31 \inmodule QtMultimedia
32 \ingroup multimedia
33 \ingroup multimedia_playback
34 \ingroup multimedia_video
35
36 The QMediaPlayer class is a high level media playback class. It can be used
37 to playback audio of video media files. The content
38 to playback is specified as a QUrl object.
39
40 \snippet multimedia-snippets/media.cpp Player
41
42 QVideoWidget can be used with QMediaPlayer for video rendering.
43
44 \sa QVideoWidget
45*/
46
47/*!
48 \qmltype MediaPlayer
49 \nativetype QMediaPlayer
50 \brief Adds media playback to a scene.
51
52 \inqmlmodule QtMultimedia
53 \ingroup multimedia_qml
54 \ingroup multimedia_audio_qml
55 \ingroup multimedia_video_qml
56
57 \qml
58 Text {
59 text: "Click Me!";
60 font.pointSize: 24;
61 width: 150; height: 50;
62
63 MediaPlayer {
64 id: playMusic
65 source: "music.wav"
66 audioOutput: AudioOutput {}
67 }
68 MouseArea {
69 anchors.fill: parent
70 onPressed: { playMusic.play() }
71 }
72 }
73 \endqml
74
75 You can use MediaPlayer together with a MultiMedia::AudioOutput to play audio content, or you can use it
76 in conjunction with a Multimedia::VideoOutput for rendering video.
77
78 \qml
79 Item {
80 MediaPlayer {
81 id: mediaplayer
82 source: "groovy_video.mp4"
83 audioOutput: AudioOutput {}
84 videoOutput: videoOutput
85 }
86
87 VideoOutput {
88 id: videoOutput
89 anchors.fill: parent
90 }
91
92 MouseArea {
93 anchors.fill: parent
94 onPressed: mediaplayer.play();
95 }
96 }
97 \endqml
98
99 \sa AudioOutput, VideoOutput
100*/
101
102void QMediaPlayerPrivate::setState(QMediaPlayer::PlaybackState toState)
103{
104 Q_Q(QMediaPlayer);
105
106 if (toState != state) {
107 const auto fromState = std::exchange(state, toState);
108 if (toState == QMediaPlayer::PlayingState || fromState == QMediaPlayer::PlayingState)
109 emit q->playingChanged(toState == QMediaPlayer::PlayingState);
110 emit q->playbackStateChanged(toState);
111 }
112}
113
114void QMediaPlayerPrivate::setStatus(QMediaPlayer::MediaStatus s)
115{
116 Q_Q(QMediaPlayer);
117
118 emit q->mediaStatusChanged(s);
119}
120
121void QMediaPlayerPrivate::setError(QMediaPlayer::Error error, const QString &errorString)
122{
123 Q_Q(QMediaPlayer);
124
125 this->error.setAndNotify(error, errorString, *q);
126}
127
128void QMediaPlayerPrivate::setMedia(QUrl media, QIODevice *stream)
129{
130 setError(QMediaPlayer::NoError, {});
131
132 if (!control)
133 return;
134
135 media = m_sourceResolver->resolve(media);
136
137 std::unique_ptr<QFile> file;
138
139 // Back ends can't play qrc files directly.
140 // If the back end supports StreamPlayback, we pass a QFile for that resource.
141 // If it doesn't, we copy the data to a temporary file and pass its path.
142 if (!media.isEmpty() && !stream && media.scheme() == QLatin1String("qrc")
143 && !control->canPlayQrc()) {
144 qrcMedia = media;
145
146 control->mediaStatusChanged(QMediaPlayer::LoadingMedia);
147
148 file.reset(new QFile(QLatin1Char(':') + media.path()));
149 if (!file->open(QFile::ReadOnly)) {
150 file.reset();
151 control->setInvalidMediaWithError(
152 QMediaPlayer::ResourceError,
153 QObject::tr("Attempting to play invalid Qt resource"));
154
155 } else if (control->streamPlaybackSupported()) {
156 control->setMedia(media, file.get());
157 } else {
158#if QT_CONFIG(temporaryfile)
159#if defined(Q_OS_ANDROID)
160 QString tempFileName = QDir::tempPath() + media.path();
161 QDir().mkpath(QFileInfo(tempFileName).path());
162 std::unique_ptr<QTemporaryFile> tempFile { QTemporaryFile::createNativeFile(*file) };
163 if (tempFile.get() == nullptr) {
164 control->setInvalidMediaWithError(
165 QMediaPlayer::ResourceError,
166 QObject::tr("Failed to establish temporary file during playback"));
167 return;
168 }
169 if (!tempFile->rename(tempFileName)) {
170 control->setInvalidMediaWithError(
171 QMediaPlayer::ResourceError,
172 QStringLiteral("Could not rename temporary file to: %1").arg(tempFileName));
173 return;
174 }
175#else
176 std::unique_ptr<QTemporaryFile> tempFile = std::make_unique<QTemporaryFile>();
177
178 // Preserve original file extension, some back ends might not load the file if it doesn't
179 // have an extension.
180 const QString suffix = QFileInfo(*file).suffix();
181 if (!suffix.isEmpty())
182 tempFile->setFileTemplate(tempFile->fileTemplate() + QLatin1Char('.') + suffix);
183
184 // Copy the qrc data into the temporary file
185 if (!tempFile->open()) {
186 control->setInvalidMediaWithError(QMediaPlayer::ResourceError,
187 tempFile->errorString());
188 qrcFile.reset();
189 return;
190 }
191 char buffer[4096];
192 while (true) {
193 qint64 len = file->read(buffer, sizeof(buffer));
194 if (len < 1)
195 break;
196 tempFile->write(buffer, len);
197 }
198 tempFile->close();
199#endif
200 file = std::move(tempFile);
201 control->setMedia(QUrl(QUrl::fromLocalFile(file->fileName())), nullptr);
202#else
203 qWarning("Qt was built with -no-feature-temporaryfile: playback from resource file is not supported!");
204#endif
205 }
206 } else {
207 qrcMedia = QUrl();
208 QUrl url = qMediaFromUserInput(media);
209 if (url.scheme() == QLatin1String("content") && !stream) {
210 file.reset(new QFile(media.url()));
211 stream = file.get();
212 }
213
214 control->setMedia(url, stream);
215 }
216
217 qrcFile.swap(file); // Cleans up any previous file
218}
219
220QList<QMediaMetaData> QMediaPlayerPrivate::trackMetaData(QPlatformMediaPlayer::TrackType s) const
221{
222 QList<QMediaMetaData> tracks;
223 if (control) {
224 int count = control->trackCount(s);
225 for (int i = 0; i < count; ++i) {
226 tracks.append(control->trackMetaData(s, i));
227 }
228 }
229 return tracks;
230}
231
232/*!
233 Constructs a QMediaPlayer instance as a child of \a{parent}.
234*/
235
236QMediaPlayer::QMediaPlayer(QObject *parent)
237 : QObject(*new QMediaPlayerPrivate, parent)
238{
239 Q_D(QMediaPlayer);
240
241 auto maybeControl = QPlatformMediaIntegration::instance()->createPlayer(this);
242 if (maybeControl) {
243 d->control = maybeControl.value();
244 d->state = d->control->state();
245 } else {
246 qWarning() << "Failed to initialize QMediaPlayer" << maybeControl.error();
247 d->setError(QMediaPlayer::ResourceError, maybeControl.error());
248 }
249}
250
251
252/*!
253 Destroys the player object.
254*/
255
256QMediaPlayer::~QMediaPlayer()
257{
258 Q_D(QMediaPlayer);
259
260 // prevents emitting audioOutputChanged and videoOutputChanged.
261 QSignalBlocker blocker(this);
262
263 // Reset audio output and video sink to ensure proper unregistering of the source
264 // To be investigated: registering of the source might be removed after switching on the ffmpeg
265 // backend;
266
267 // Workaround to prevent freeze in GStreamer when setting audioOutput while stopped
268 if (d->control)
269 d->control->qmediaplayerDestructorCalled = true;
270 setAudioOutput(nullptr);
271
272 d->setVideoSink(nullptr);
273 delete d->control;
274}
275
276QUrl QMediaPlayer::source() const
277{
278 Q_D(const QMediaPlayer);
279
280 return d->source;
281}
282
283/*!
284 Returns the stream source of media data.
285
286 This is only valid if a stream was passed to setSource().
287
288 \sa setSource()
289*/
290
291const QIODevice *QMediaPlayer::sourceDevice() const
292{
293 Q_D(const QMediaPlayer);
294
295 return d->stream;
296}
297
298/*!
299 \property QMediaPlayer::playbackState
300
301 Returns the \l{QMediaPlayer::}{PlaybackState}.
302
303 \sa playing
304*/
305QMediaPlayer::PlaybackState QMediaPlayer::playbackState() const
306{
307 Q_D(const QMediaPlayer);
308
309 // In case if EndOfMedia status is already received
310 // but state is not.
311 if (d->control
312 && d->control->mediaStatus() == QMediaPlayer::EndOfMedia
313 && d->state != d->control->state()) {
314 return d->control->state();
315 }
316
317 return d->state;
318}
319
320QMediaPlayer::MediaStatus QMediaPlayer::mediaStatus() const
321{
322 Q_D(const QMediaPlayer);
323 return d->control ? d->control->mediaStatus() : NoMedia;
324}
325
326/*!
327 Returns the duration of the current media in ms.
328
329 Returns 0 if the media player doesn't have a valid media file or stream.
330 For live streams, the duration usually changes during playback as more
331 data becomes available.
332*/
333qint64 QMediaPlayer::duration() const
334{
335 Q_D(const QMediaPlayer);
336 return d->control ? d->control->duration() : 0;
337}
338
339/*!
340 Returns the current position inside the media being played back in ms.
341
342 Returns 0 if the media player doesn't have a valid media file or stream.
343 For live streams, the duration usually changes during playback as more
344 data becomes available.
345*/
346qint64 QMediaPlayer::position() const
347{
348 Q_D(const QMediaPlayer);
349 return d->control ? d->control->position() : 0;
350}
351
352/*!
353 Returns a number between 0 and 1 when buffering data.
354
355 0 means that there is no buffered data available, playback is usually
356 stalled in this case. Playback will resume once the buffer reaches 1,
357 meaning enough data has been buffered to be able to resume playback.
358
359 bufferProgress() will always return 1 for local files.
360*/
361float QMediaPlayer::bufferProgress() const
362{
363 Q_D(const QMediaPlayer);
364 return d->control ? d->control->bufferProgress() : 0;
365}
366
367/*!
368 Returns a QMediaTimeRange describing the currently buffered data.
369
370 When streaming media from a remote source, different parts of the media
371 file can be available locally. The returned QMediaTimeRange object describes
372 the time ranges that are buffered and available for immediate playback.
373
374 \sa QMediaTimeRange
375*/
376QMediaTimeRange QMediaPlayer::bufferedTimeRange() const
377{
378 Q_D(const QMediaPlayer);
379 return d->control ? d->control->availablePlaybackRanges() : QMediaTimeRange{};
380}
381
382/*!
383 \qmlproperty bool QtMultimedia::MediaPlayer::hasAudio
384
385 This property holds whether the media contains audio.
386*/
387
388/*!
389 \property QMediaPlayer::hasAudio
390 \brief This property holds whether the media contains audio.
391*/
392bool QMediaPlayer::hasAudio() const
393{
394 Q_D(const QMediaPlayer);
395 return d->control && d->control->isAudioAvailable();
396}
397
398/*!
399 \qmlproperty bool QtMultimedia::MediaPlayer::hasVideo
400
401 This property holds whether the media contains video.
402*/
403
404/*!
405 \property QMediaPlayer::hasVideo
406 \brief This property holds whether the media contains video.
407*/
408bool QMediaPlayer::hasVideo() const
409{
410 Q_D(const QMediaPlayer);
411 return d->control && d->control->isVideoAvailable();
412}
413
414/*!
415 Returns true if the media is seekable. Most file based media files are seekable,
416 but live streams usually are not.
417
418 \sa position
419*/
420bool QMediaPlayer::isSeekable() const
421{
422 Q_D(const QMediaPlayer);
423 return d->control && d->control->isSeekable();
424}
425
426bool QMediaPlayer::isPlaying() const
427{
428 Q_D(const QMediaPlayer);
429 return d->state == QMediaPlayer::PlayingState;
430}
431
432/*!
433 Returns the current playback rate.
434*/
435qreal QMediaPlayer::playbackRate() const
436{
437 Q_D(const QMediaPlayer);
438 return d->control ? d->control->playbackRate() : 0.;
439}
440
441/*!
442 \enum QMediaPlayer::Loops
443
444 Some predefined constants for the \l loops property.
445
446 \value Infinite Loop forever.
447 \value Once Play the media once (the default).
448*/
449
450/*!
451 \property QMediaPlayer::loops
452
453 Determines how often the media is played before the player stops.
454 Set to QMediaPlayer::Infinite to loop the current media file forever.
455
456 The default value is \c 1. Setting this property to \c 0 has no effect.
457*/
458
459/*!
460 \qmlproperty int QtMultimedia::MediaPlayer::loops
461
462 Determines how often the media is played before the player stops.
463 Set to MediaPlayer::Infinite to loop the current media file forever.
464
465 The default value is \c 1. Setting this property to \c 0 has no effect.
466*/
467int QMediaPlayer::loops() const
468{
469 Q_D(const QMediaPlayer);
470 return d->control ? d->control->loops() : 1;
471}
472
473void QMediaPlayer::setLoops(int loops)
474{
475 Q_D(QMediaPlayer);
476 if (loops == 0)
477 return;
478 if (d->control)
479 d->control->setLoops(loops);
480}
481
482/*!
483 Returns the current error state.
484*/
485QMediaPlayer::Error QMediaPlayer::error() const
486{
487 return d_func()->error.code();
488}
489
490/*!
491 \qmlproperty string QtMultimedia::MediaPlayer::errorString
492
493 This property holds a string describing the current error condition in more
494 detail.
495*/
496
497/*!
498 \property QMediaPlayer::errorString
499 \brief This property holds a string describing the current error condition in
500 more detail.
501*/
502QString QMediaPlayer::errorString() const
503{
504 return d_func()->error.description();
505}
506
507/*!
508 \qmlmethod void QtMultimedia::MediaPlayer::play()
509
510 Starts or resumes playback of the media.
511
512 Sets the \l playbackState property to PlayingState, and changes
513 \l playing to \c true.
514*/
515
516/*!
517 Start or resume playing the current source.
518
519 \sa pause(), stop()
520*/
521void QMediaPlayer::play()
522{
523 Q_D(QMediaPlayer);
524
525 if (!d->control)
526 return;
527
528 d->control->play();
529}
530
531/*!
532 \qmlmethod void QtMultimedia::MediaPlayer::pause()
533
534 Pauses playback of the media.
535
536 Sets the \l playbackState property to PausedState,
537 and changes \l playing to \c false.
538*/
539
540/*!
541 Pause playing the current source.
542
543 \sa play(), stop()
544*/
545void QMediaPlayer::pause()
546{
547 Q_D(QMediaPlayer);
548
549 if (d->control)
550 d->control->pause();
551}
552
553/*!
554 \qmlmethod void QtMultimedia::MediaPlayer::stop()
555
556 Stops playback of the media.
557
558 Sets the \l playbackState property to StoppedState,
559 and changes \l playing to \c false.
560*/
561
562/*!
563 Stop playing, and reset the play position to the beginning.
564
565 \sa play(), pause()
566*/
567void QMediaPlayer::stop()
568{
569 Q_D(QMediaPlayer);
570
571 if (d->control)
572 d->control->stop();
573}
574
575void QMediaPlayer::setPosition(qint64 position)
576{
577 Q_D(QMediaPlayer);
578
579 if (!d->control)
580 return;
581 if (!d->control->isSeekable())
582 return;
583 d->control->setPosition(qMax(position, 0ll));
584}
585
586void QMediaPlayer::setPlaybackRate(qreal rate)
587{
588 Q_D(QMediaPlayer);
589
590 if (d->control)
591 d->control->setPlaybackRate(rate);
592}
593
594/*!
595 \qmlproperty url QtMultimedia::MediaPlayer::source
596
597 This property holds the source URL of the media.
598
599 \snippet multimedia-snippets/qtvideosink.qml complete
600
601 \sa QMediaPlayer::setSource()
602*/
603
604/*!
605 Sets the current \a source.
606
607 Setting the media to a null QUrl will cause the player to discard all
608 information relating to the current media source and to cease all I/O operations related
609 to that media. Setting the media will stop the playback.
610
611 \note This function returns immediately after recording the specified source of the media.
612 It does not wait for the media to finish loading and does not check for errors. Listen for
613 the mediaStatusChanged() and error() signals to be notified when the media is loaded and
614 when an error occurs during loading.
615
616 \note FFmpeg, used by the FFmpeg media backend, restricts use of nested protocols for
617 security reasons. In controlled environments where all inputs are trusted, the list of
618 approved protocols can be overridden using the QT_FFMPEG_PROTOCOL_WHITELIST environment
619 variable. This environment variable is Qt's private API and can change between patch
620 releases without notice.
621*/
622
623void QMediaPlayer::setSource(const QUrl &source)
624{
625 Q_D(QMediaPlayer);
626 stop();
627
628 if (d->source == source && d->stream == nullptr)
629 return;
630
631 d->source = source;
632 d->stream = nullptr;
633
634 d->setMedia(source, nullptr);
635 emit sourceChanged(d->source);
636}
637
638/*!
639 Sets the current source \a device.
640
641 The media data will be read from \a device. The \a sourceUrl can be provided
642 to resolve additional information about the media, mime type etc. The
643 \a device must be open and readable.
644
645 For macOS the \a device should also be seek-able.
646
647 \note This function returns immediately after recording the specified source
648 of the media. It does not wait for the media to finish loading and does not
649 check for errors. Listen for the mediaStatusChanged() and error() signals to
650 be notified when the media is loaded, and if an error occurs during loading.
651*/
652void QMediaPlayer::setSourceDevice(QIODevice *device, const QUrl &sourceUrl)
653{
654 Q_D(QMediaPlayer);
655 stop();
656
657 if (d->source == sourceUrl && d->stream == device)
658 return;
659
660 d->source = sourceUrl;
661 d->stream = device;
662
663 d->setMedia(d->source, device);
664 emit sourceChanged(d->source);
665}
666
667/*!
668 \qmlproperty QAudioBufferOutput QtMultimedia::MediaPlayer::audioBufferOutput
669 \since 6.8
670
671 This property holds the target audio buffer output.
672
673 Normal usage of MediaPlayer from QML should not require using this property.
674
675 \sa QMediaPlayer::audioBufferOutput()
676*/
677
678/*!
679 \property QMediaPlayer::audioBufferOutput
680 \since 6.8
681 \brief The output audio buffer used by the media player.
682
683 Sets an audio buffer \a output to the media player.
684
685 If \l QAudioBufferOutput is specified and the media source
686 contains an audio stream, the media player, it will emit
687 the signal \l{QAudioBufferOutput::audioBufferReceived} with
688 audio buffers containing decoded audio data. At the end of
689 the audio stream, \c QMediaPlayer emits an empty \l QAudioBuffer.
690
691 \c QMediaPlayer emits outputs audio buffers at the same time as it
692 pushes the matching data to the audio output if it's specified.
693 However, the sound can be played with a small delay due to
694 audio bufferization.
695
696 The format of emitted audio buffers is taken from the
697 specified \a output or from the matching audio stream
698 if the \a output returns an invalid format. Emitted
699 audio data is not scaled depending on the current playback rate.
700
701 Potential use cases of utilizing \c QAudioBufferOutput
702 with \c QMediaPlayer might be:
703 \list
704 \li Audio visualization. If the playback rate of the media player
705 is not \c 1, you may scale the output image dimensions,
706 or image update interval according to the requirements
707 of the visualizer.
708 \li Any AI sound processing, e.g. voice recognition.
709 \li Sending the data to external audio output.
710 Playback rate changing, synchronization with video, and manual
711 flushing on stoping and seeking should be considered.
712 We don't recommend using the audio buffer output
713 for this purpose unless you have a strong reason for this.
714 \endlist
715
716*/
717void QMediaPlayer::setAudioBufferOutput(QAudioBufferOutput *output)
718{
719 Q_D(QMediaPlayer);
720
721 QAudioBufferOutput *oldOutput = d->audioBufferOutput;
722 if (oldOutput == output)
723 return;
724
725 d->audioBufferOutput = output;
726
727 if (oldOutput) {
728 auto oldPlayer = QAudioBufferOutputPrivate::exchangeMediaPlayer(*oldOutput, this);
729 if (oldPlayer)
730 oldPlayer->setAudioBufferOutput(nullptr);
731 }
732
733 if (d->control)
734 d->control->setAudioBufferOutput(output);
735
736 emit audioBufferOutputChanged();
737}
738
739QAudioBufferOutput *QMediaPlayer::audioBufferOutput() const
740{
741 Q_D(const QMediaPlayer);
742 return d->audioBufferOutput;
743}
744
745/*!
746 \qmlproperty AudioOutput QtMultimedia::MediaPlayer::audioOutput
747
748 This property holds the target audio output.
749 Accepts one AudioOutput elements.
750
751 \sa QMediaPlayer::setAudioOutput()
752*/
753
754
755/*!
756 \property QMediaPlayer::audioOutput
757 \brief The audio output device used by the media player.
758
759 The current audio output to be used when playing back media. Setting
760 a new audio output will replace the currently used output.
761
762 Setting this property to \c nullptr will disable any audio output.
763*/
764void QMediaPlayer::setAudioOutput(QAudioOutput *output)
765{
766 Q_D(QMediaPlayer);
767 auto oldOutput = d->audioOutput;
768 if (oldOutput == output)
769 return;
770 d->audioOutput = output;
771 if (d->control)
772 d->control->setAudioOutput(nullptr);
773 if (oldOutput)
774 oldOutput->setDisconnectFunction({});
775 if (output) {
776 output->setDisconnectFunction([this](){ setAudioOutput(nullptr); });
777 if (d->control)
778 d->control->setAudioOutput(output->handle());
779 }
780 emit audioOutputChanged();
781}
782
783QAudioOutput *QMediaPlayer::audioOutput() const
784{
785 Q_D(const QMediaPlayer);
786 return d->audioOutput;
787}
788
789/*!
790 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::audioTracks
791
792 This property holds a list of metadata.
793 Each index refers to an audio track.
794
795 The metadata holds properties describing the individual tracks. For
796 audio tracks the \l{QMediaMetaData}{Language} is usually the most
797 important property.
798
799 \sa mediaMetaData
800*/
801
802/*!
803 \property QMediaPlayer::audioTracks
804
805 Lists the set of available audio tracks inside the media.
806
807 The QMediaMetaData returned describes the properties of individual
808 tracks.
809
810 Different audio tracks can for example contain audio in different languages.
811*/
812QList<QMediaMetaData> QMediaPlayer::audioTracks() const
813{
814 Q_D(const QMediaPlayer);
815 return d->trackMetaData(QPlatformMediaPlayer::AudioStream);
816}
817
818/*!
819 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::videoTracks
820
821 This property holds a list of metadata.
822 Each index refers to a video track.
823
824 The metadata holds properties describing the individual tracks.
825
826 \sa mediaMetaData
827*/
828
829/*!
830 \property QMediaPlayer::videoTracks
831
832 Lists the set of available video tracks inside the media.
833
834 The QMediaMetaData returned describes the properties of individual
835 tracks.
836*/
837QList<QMediaMetaData> QMediaPlayer::videoTracks() const
838{
839 Q_D(const QMediaPlayer);
840 return d->trackMetaData(QPlatformMediaPlayer::VideoStream);
841}
842
843/*!
844 \qmlproperty list<mediaMetaData> QtMultimedia::MediaPlayer::subtitleTracks
845
846 This property holds a list of metadata.
847 Each index refers to a subtitle track.
848
849 The metadata holds properties describing the individual tracks. For
850 subtitle tracks the \l{QMediaMetaData}{Language} is usually the most
851 important property.
852
853 \sa mediaMetaData
854*/
855
856/*!
857 \property QMediaPlayer::subtitleTracks
858
859 Lists the set of available subtitle tracks inside the media.
860
861 The QMediaMetaData returned describes the properties of individual
862 tracks.
863*/
864QList<QMediaMetaData> QMediaPlayer::subtitleTracks() const
865{
866 Q_D(const QMediaPlayer);
867 return d->trackMetaData(QPlatformMediaPlayer::SubtitleStream);
868}
869
870/*!
871 \qmlproperty int QtMultimedia::MediaPlayer::activeAudioTrack
872
873 This property holds the track number of the currently active audio track.
874 Set to \c{-1} to disable audio track.
875
876 The default property value is \c{0}: the first audio track.
877*/
878
879/*!
880 \property QMediaPlayer::activeAudioTrack
881 \brief Returns the currently active audio track.
882
883 By default, the first available audio track will be chosen.
884
885 Set \a index to \c -1 to disable all audio tracks.
886*/
887int QMediaPlayer::activeAudioTrack() const
888{
889 Q_D(const QMediaPlayer);
890 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::AudioStream) : 0;
891}
892
893/*!
894 \since 6.2
895 \qmlproperty int QtMultimedia::MediaPlayer::activeVideoTrack
896
897 This property holds the track number of the currently active video audio track.
898 Set to \c{-1} to disable video track.
899
900 The default property value is \c{0}: the first video track.
901*/
902
903/*!
904 \property QMediaPlayer::activeVideoTrack
905 \brief Returns the currently active video track.
906
907 By default, the first available audio track will be chosen.
908
909 Set \a index to \c -1 to disable all video tracks.
910*/
911int QMediaPlayer::activeVideoTrack() const
912{
913 Q_D(const QMediaPlayer);
914 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::VideoStream) : -1;
915}
916
917/*!
918 \since 6.2
919 \qmlproperty int QtMultimedia::MediaPlayer::activeSubtitleTrack
920
921 This property holds the track number of the currently active subtitle track.
922 Set to \c{-1} to disable subtitle track.
923
924 The default property value is \c{-1}: no subtitles active.
925*/
926
927/*!
928 \property QMediaPlayer::activeSubtitleTrack
929 \brief Returns the currently active subtitle track.
930
931 Set \a index to \c -1 to disable subtitles.
932
933 Subtitles are disabled by default.
934*/
935int QMediaPlayer::activeSubtitleTrack() const
936{
937 Q_D(const QMediaPlayer);
938 return d->control ? d->control->activeTrack(QPlatformMediaPlayer::SubtitleStream) : -1;
939}
940
941void QMediaPlayer::setActiveAudioTrack(int index)
942{
943 Q_D(QMediaPlayer);
944 if (!d->control)
945 return;
946
947 if (activeAudioTrack() == index)
948 return;
949 d->control->setActiveTrack(QPlatformMediaPlayer::AudioStream, index);
950}
951
952void QMediaPlayer::setActiveVideoTrack(int index)
953{
954 Q_D(QMediaPlayer);
955 if (!d->control)
956 return;
957
958 if (activeVideoTrack() == index)
959 return;
960 d->control->setActiveTrack(QPlatformMediaPlayer::VideoStream, index);
961}
962
963void QMediaPlayer::setActiveSubtitleTrack(int index)
964{
965 Q_D(QMediaPlayer);
966 if (!d->control)
967 return;
968
969 if (activeSubtitleTrack() == index)
970 return;
971 d->control->setActiveTrack(QPlatformMediaPlayer::SubtitleStream, index);
972}
973
974/*!
975 \qmlproperty VideoOutput QtMultimedia::MediaPlayer::videoOutput
976
977 This property holds the target video output.
978 Accepts one VideoOutput elements.
979
980 \sa QMediaPlayer::setVideoOutput()
981*/
982
983/*!
984 \property QMediaPlayer::videoOutput
985 \brief The video output to be used by the media player.
986
987 A media player can only have one video output attached, so
988 setting this property will replace the previously connected
989 video output.
990
991 Setting this property to \c nullptr will disable video output.
992*/
993QObject *QMediaPlayer::videoOutput() const
994{
995 Q_D(const QMediaPlayer);
996 return d->videoOutput;
997}
998
999void QMediaPlayer::setVideoOutput(QObject *output)
1000{
1001 Q_D(QMediaPlayer);
1002 if (d->videoOutput == output)
1003 return;
1004
1005 auto *sink = qobject_cast<QVideoSink *>(output);
1006 if (!sink && output) {
1007 auto *mo = output->metaObject();
1008 mo->invokeMethod(output, "videoSink", Q_RETURN_ARG(QVideoSink *, sink));
1009 }
1010 d->videoOutput = output;
1011 d->setVideoSink(sink);
1012}
1013
1014/*!
1015 Sets \a sink to be the QVideoSink instance to
1016 retrieve video data.
1017*/
1018void QMediaPlayer::setVideoSink(QVideoSink *sink)
1019{
1020 Q_D(QMediaPlayer);
1021 d->videoOutput = nullptr;
1022 d->setVideoSink(sink);
1023}
1024
1025/*!
1026 Returns the QVideoSink instance.
1027*/
1028QVideoSink *QMediaPlayer::videoSink() const
1029{
1030 Q_D(const QMediaPlayer);
1031 return d->videoSink;
1032}
1033
1034
1035#if 0
1036/*
1037 \since 5.15
1038 Sets multiple video sinks as the video output of a media player.
1039 This allows the media player to render video frames on several outputs.
1040
1041 If a video output has already been set on the media player the new surfaces
1042 will replace it.
1043*/
1044void QMediaPlayer::setVideoOutput(const QList<QVideoSink *> &sinks)
1045{
1046 // ### IMPLEMENT ME
1047 Q_UNUSED(sinks);
1048// setVideoOutput(!surfaces.empty() ? new QVideoSurfaces(surfaces, this) : nullptr);
1049}
1050#endif
1051
1052/*!
1053 Returns true if the media player is supported on this platform.
1054*/
1055bool QMediaPlayer::isAvailable() const
1056{
1057 Q_D(const QMediaPlayer);
1058 return bool(d->control);
1059}
1060
1061/*!
1062 \qmlproperty mediaMetaData QtMultimedia::MediaPlayer::metaData
1063
1064 Returns meta data for the current media used by the media player.
1065
1066 Meta data can contain information such as the title of the video or its creation date.
1067
1068 \note The Windows implementation provides metadata only for media located on the local file
1069 system.
1070*/
1071
1072/*!
1073 \property QMediaPlayer::metaData
1074
1075 Returns meta data for the current media used by the media player.
1076
1077 Meta data can contain information such as the title of the video or its creation date.
1078
1079 \note The Windows implementation provides metadata only for media located on the local file
1080 system.
1081*/
1082QMediaMetaData QMediaPlayer::metaData() const
1083{
1084 Q_D(const QMediaPlayer);
1085 return d->control ? d->control->metaData() : QMediaMetaData{};
1086}
1087
1088/*!
1089 \qmlproperty bool QtMultimedia::MediaPlayer::pitchCompensation
1090 \since 6.10
1091
1092 This property holds whether pitch compensation is enabled.
1093*/
1094
1095/*!
1096 \property QMediaPlayer::pitchCompensation
1097 \brief The pitch compensation status of the media player.
1098 \since 6.10
1099
1100 Indicates whether pitch compensation is enabled. When enabled, changing the playback rate
1101 will not affect the pitch of the audio signal.
1102
1103 \note The pitch compensation will increase the CPU load of the QMediaPlayer.
1104
1105 By default is \c{true} if pitch compensation, is available, else \c{false}.
1106*/
1107
1108/*!
1109 Returns the state of pitch compensation.
1110 \since 6.10
1111*/
1112bool QMediaPlayer::pitchCompensation() const
1113{
1114 Q_D(const QMediaPlayer);
1115 return d->control ? d->control->pitchCompensation() : false;
1116}
1117
1118/*!
1119 Sets the state (\a enabled or disabled) of pitch compensation. This only
1120 has an effect if the audio pitch compensation can be configured on the
1121 backend at runtime.
1122 \since 6.10
1123*/
1124void QMediaPlayer::setPitchCompensation(bool enabled) const
1125{
1126 Q_D(const QMediaPlayer);
1127 if (d->control)
1128 d->control->setPitchCompensation(enabled);
1129}
1130
1131/*!
1132 \enum QMediaPlayer::PitchCompensationAvailability
1133 \since 6.10
1134
1135 Availablility of pitch compensation.
1136
1137 Different backends have different behavior regarding pitch compensation when changing
1138 playback rate.
1139
1140 \value AlwaysOn The media player is always performing pitch compensation.
1141 \value Available The media player can be configured to use pitch compensation.
1142 If pitch compensation is available on the current platform, it will be enabled by default,
1143 but users can disable if needed.
1144 \value Unavailable The media player is not able to perform pitch compensation
1145 on the current platform.
1146*/
1147
1148/*!
1149 \qmlproperty enumeration QtMultimedia::MediaPlayer::pitchCompensationAvailability
1150 \since 6.10
1151
1152 Indicates the availability of pitch compensation of the \c MediaPlayer on the current backend.
1153 The enumeration \c PitchCompensationAvailability is scoped.
1154
1155 \qmlenumeratorsfrom QMediaPlayer::PitchCompensationAvailability
1156*/
1157
1158/*!
1159 \property QMediaPlayer::pitchCompensationAvailability
1160 \brief The pitch compensation availability of the current QtMultimedia backend.
1161 \since 6.10
1162
1163 Indicates the availability of pitch compensation of the QMediaPlayer on the current backend.
1164
1165 \note Different backends may have different behavior.
1166
1167 For more information, see \l{QMediaPlayer::PitchCompensationAvailability}.
1168*/
1169
1170/*!
1171 Returns availability of pitch compensation of the current backend.
1172 \since 6.10
1173*/
1174
1175QMediaPlayer::PitchCompensationAvailability QMediaPlayer::pitchCompensationAvailability() const
1176{
1177 Q_D(const QMediaPlayer);
1178 return d->control ? d->control->pitchCompensationAvailability()
1179 : PitchCompensationAvailability::Unavailable;
1180}
1181
1182/*!
1183 \qmlproperty playbackOptions MediaPlayer::playbackOptions
1184 \since 6.10
1185
1186 This property exposes the \l playbackOptions API that gives low-level control of media playback
1187 options. Although we strongly recommend to rely on the default settings of \l MediaPlayer,
1188 this API can be used to optimize media playback for specific use cases where the default
1189 options are not ideal.
1190
1191 Playback options take effect the next time \l MediaPlayer::source is changed.
1192*/
1193
1194/*!
1195 \property QMediaPlayer::playbackOptions
1196 \brief Advanced playback options used to configure media playback and decoding.
1197 \since 6.10
1198
1199 This property exposes the \l QPlaybackOptions API that gives low-level control of media
1200 playback options. Although we strongly recommend to rely on the default settings of
1201 \l QMediaPlayer, this API can be used to optimize media playback for specific use cases where
1202 the default options are not ideal.
1203
1204 Playback options take effect the next time \l QMediaPlayer::setSource() is called.
1205*/
1206
1207QPlaybackOptions QMediaPlayer::playbackOptions() const
1208{
1209 Q_D(const QMediaPlayer);
1210 return d->playbackOptions;
1211}
1212
1213void QMediaPlayer::setPlaybackOptions(const QPlaybackOptions &options)
1214{
1215 Q_D(QMediaPlayer);
1216 if (std::exchange(d->playbackOptions, options) != options)
1217 emit playbackOptionsChanged();
1218}
1219
1220void QMediaPlayer::resetPlaybackOptions()
1221{
1222 Q_D(QMediaPlayer);
1223 QPlaybackOptions defaultOptions{ };
1224 if (std::exchange(d->playbackOptions, defaultOptions) != defaultOptions)
1225 emit playbackOptionsChanged();
1226}
1227
1228// Enums
1229/*!
1230 \enum QMediaPlayer::PlaybackState
1231
1232 Defines the current state of a media player.
1233
1234 \value StoppedState The media player is not playing content, playback will begin from the start
1235 of the current track.
1236 \value PlayingState The media player is currently playing content. This indicates the same as the \l playing property.
1237 \value PausedState The media player has paused playback, playback of the current track will
1238 resume from the position the player was paused at.
1239*/
1240
1241/*!
1242 \qmlproperty enumeration QtMultimedia::MediaPlayer::playbackState
1243
1244 This property holds the state of media playback. It can be one of the following:
1245
1246 \table
1247 \header \li Property value
1248 \li Description
1249 \row \li PlayingState
1250 \li The media is currently playing. This indicates the same as the \l playing property.
1251 \row \li PausedState
1252 \li Playback of the media has been suspended.
1253 \row \li StoppedState
1254 \li Playback of the media is yet to begin.
1255 \endtable
1256*/
1257
1258/*!
1259 \qmlsignal QtMultimedia::MediaPlayer::playbackStateChanged()
1260
1261 This signal is emitted when the \l playbackState property is altered.
1262*/
1263
1264/*!
1265 \qmlsignal QtMultimedia::MediaPlayer::playingChanged()
1266
1267 This signal is emitted when the \l playing property changes.
1268*/
1269
1270/*!
1271 \enum QMediaPlayer::MediaStatus
1272
1273 Defines the status of a media player's current media.
1274
1275 \value NoMedia The is no current media. The player is in the StoppedState.
1276 \value LoadingMedia The current media is being loaded. The player may be in any state.
1277 \value LoadedMedia The current media has been loaded. The player is in the StoppedState.
1278 \value StalledMedia Playback of the current media has stalled due to insufficient buffering or
1279 some other temporary interruption. The player is in the PlayingState or PausedState.
1280 \value BufferingMedia The player is buffering data but has enough data buffered for playback to
1281 continue for the immediate future. The player is in the PlayingState or PausedState.
1282 \value BufferedMedia The player has fully buffered the current media. The player is in the
1283 PlayingState or PausedState.
1284 \value EndOfMedia Playback has reached the end of the current media. The player is in the
1285 StoppedState.
1286 \value InvalidMedia The current media cannot be played. The player is in the StoppedState.
1287*/
1288
1289/*!
1290 \qmlproperty enumeration QtMultimedia::MediaPlayer::mediaStatus
1291
1292 This property holds the status of media loading. It can be one of the following:
1293
1294 \qmlenumeratorsfrom QMediaPlayer::MediaStatus
1295*/
1296
1297/*!
1298 \qmlproperty enumeration QtMultimedia::MediaPlayer::error
1299
1300 This property holds the error state of the audio. It can be one of the following.
1301
1302 \qmlenumeratorsfrom QMediaPlayer::Error
1303*/
1304
1305/*!
1306 \enum QMediaPlayer::Error
1307
1308 Defines a media player error condition.
1309
1310 \value NoError No error has occurred.
1311 \value ResourceError A media resource couldn't be resolved.
1312 \value FormatError The format of a media resource isn't (fully) supported. Playback may still
1313 be possible, but without an audio or video component.
1314 \value NetworkError A network error occurred.
1315 \value AccessDeniedError There are not the appropriate permissions to play a media resource.
1316*/
1317
1318/*!
1319 \qmlsignal QtMultimedia::MediaPlayer::errorOccurred(error, errorString)
1320
1321 This signal is emitted when an \a error has occurred. The \a errorString
1322 parameter may contain more detailed information about the error.
1323
1324 \sa QMediaPlayer::Error
1325*/
1326
1327/*!
1328 \fn QMediaPlayer::errorOccurred(QMediaPlayer::Error error, const QString &errorString)
1329
1330 Signals that an \a error condition has occurred, with \a errorString
1331 containing a description of the error.
1332
1333 \sa errorString()
1334*/
1335
1336/*!
1337 \fn QMediaPlayer::mediaStatusChanged(QMediaPlayer::MediaStatus status)
1338
1339 Signals that the \a status of the current media has changed.
1340
1341 \sa mediaStatus()
1342*/
1343
1344/*!
1345 \fn void QMediaPlayer::sourceChanged(const QUrl &media);
1346
1347 Signals that the media source has been changed to \a media.
1348*/
1349
1350/*!
1351 \fn void QMediaPlayer::playbackRateChanged(qreal rate);
1352
1353 Signals the playbackRate has changed to \a rate.
1354*/
1355
1356/*!
1357 \fn void QMediaPlayer::seekableChanged(bool seekable);
1358
1359 Signals the \a seekable status of the player object has changed.
1360*/
1361
1362// Properties
1363/*!
1364 \property QMediaPlayer::error
1365 \brief a string describing the last error condition.
1366
1367 \sa error()
1368*/
1369
1370/*!
1371 \property QMediaPlayer::source
1372 \brief the active media source being used by the player object.
1373
1374 The player object will use the QUrl for selection of the content to
1375 be played.
1376
1377 By default this property has a null QUrl.
1378
1379 Setting this property to a null QUrl will cause the player to discard all
1380 information relating to the current media source and to cease all I/O operations related
1381 to that media.
1382
1383 \sa QUrl
1384*/
1385
1386/*!
1387 \property QMediaPlayer::mediaStatus
1388 \brief the status of the current media stream.
1389
1390 The stream status describes how the playback of the current stream is
1391 progressing.
1392
1393 By default this property is QMediaPlayer::NoMedia
1394
1395*/
1396
1397/*!
1398 \qmlproperty int QtMultimedia::MediaPlayer::duration
1399
1400 This property holds the duration of the media in milliseconds.
1401
1402 If the media doesn't have a fixed duration (a live stream for example) this
1403 will be set to \c{0}.
1404*/
1405
1406/*!
1407 \property QMediaPlayer::duration
1408 \brief the duration of the current media.
1409
1410 The value is the total playback time in milliseconds of the current media.
1411 The value may change across the life time of the QMediaPlayer object and
1412 may not be available when initial playback begins, connect to the
1413 durationChanged() signal to receive status notifications.
1414*/
1415
1416/*!
1417 \qmlproperty int QtMultimedia::MediaPlayer::position
1418
1419 The value is the current playback position, expressed in milliseconds since
1420 the beginning of the media. Periodically changes in the position will be
1421 indicated with the positionChanged() signal.
1422
1423 If the \l seekable property is true, this property can be set to milliseconds.
1424*/
1425
1426/*!
1427 \property QMediaPlayer::position
1428 \brief the playback position of the current media.
1429
1430 The value is the current playback position, expressed in milliseconds since
1431 the beginning of the media. Periodically changes in the position will be
1432 indicated with the positionChanged() signal.
1433
1434 If the \l seekable property is true, this property can be set to milliseconds.
1435*/
1436
1437/*!
1438 \qmlproperty real QtMultimedia::MediaPlayer::bufferProgress
1439
1440 This property holds how much of the data buffer is currently filled,
1441 from \c 0.0 (empty) to \c 1.0 (full).
1442
1443 Playback can start or resume only when the buffer is entirely filled.
1444 When the buffer is filled, \c MediaPlayer.Buffered is true.
1445 When buffer progress is between \c 0.0 and \c 1.0, \c MediaPlayer.Buffering
1446 is set to \c{true}.
1447
1448 A value lower than \c 1.0 implies that the property \c MediaPlayer.StalledMedia
1449 is \c{true}.
1450
1451 \sa mediaStatus
1452 */
1453
1454/*!
1455 \property QMediaPlayer::bufferProgress
1456 \brief the percentage of the temporary buffer filled before playback begins or resumes, from
1457 \c 0. (empty) to \c 1. (full).
1458
1459 When the player object is buffering; this property holds the percentage of
1460 the temporary buffer that is filled. The buffer will need to reach 100%
1461 filled before playback can start or resume, at which time mediaStatus() will return
1462 BufferedMedia or BufferingMedia. If the value is anything lower than \c 100, mediaStatus() will
1463 return StalledMedia.
1464
1465 \sa mediaStatus()
1466*/
1467
1468/*!
1469 \qmlproperty bool QtMultimedia::MediaPlayer::seekable
1470
1471 This property holds whether the \l position of the media can be changed.
1472*/
1473
1474/*!
1475 \property QMediaPlayer::seekable
1476 \brief the seek-able status of the current media
1477
1478 If seeking is supported this property will be true; false otherwise. The
1479 status of this property may change across the life time of the QMediaPlayer
1480 object, use the seekableChanged signal to monitor changes.
1481*/
1482
1483/*!
1484 \qmlproperty bool QtMultimedia::MediaPlayer::playing
1485 \since 6.5
1486
1487 Indicates whether the media is currently playing.
1488
1489 \sa playbackState
1490*/
1491
1492/*!
1493 \property QMediaPlayer::playing
1494 \brief Whether the media is playing.
1495 \since 6.5
1496
1497 \sa playbackState, PlayingState
1498*/
1499
1500/*!
1501 \qmlproperty real QtMultimedia::MediaPlayer::playbackRate
1502
1503 This property holds the rate at which media is played at as a multiple of
1504 the normal rate.
1505
1506 For more information, see \l{QMediaPlayer::playbackRate}.
1507
1508 Defaults to \c{1.0}.
1509*/
1510
1511/*!
1512 \property QMediaPlayer::playbackRate
1513 \brief the playback rate of the current media.
1514
1515 This value is a multiplier applied to the media's standard playback
1516 rate. By default this value is 1.0, indicating that the media is
1517 playing at the standard speed. Values higher than 1.0 will increase
1518 the playback speed, while values between 0.0 and 1.0 results in
1519 slower playback. Negative playback rates are not supported.
1520
1521 Not all playback services support change of the playback rate. It is
1522 framework defined as to the status and quality of audio and video
1523 while fast forwarding or rewinding.
1524*/
1525
1526/*!
1527 \fn void QMediaPlayer::durationChanged(qint64 duration)
1528
1529 Signals the duration of the content has changed to \a duration, expressed in milliseconds.
1530*/
1531
1532/*!
1533 \fn void QMediaPlayer::positionChanged(qint64 position)
1534
1535 Signals the position of the content has changed to \a position, expressed in
1536 milliseconds.
1537*/
1538
1539/*!
1540 \fn void QMediaPlayer::hasVideoChanged(bool videoAvailable)
1541
1542 Signals the availability of visual content has changed to \a videoAvailable.
1543*/
1544
1545/*!
1546 \fn void QMediaPlayer::hasAudioChanged(bool available)
1547
1548 Signals the availability of audio content has changed to \a available.
1549*/
1550
1551/*!
1552 \fn void QMediaPlayer::bufferProgressChanged(float filled)
1553
1554 Signals the amount of the local buffer \a filled as a number between 0 and 1.
1555*/
1556
1557QT_END_NAMESPACE
1558
1559#include "moc_qmediaplayer.cpp"
QPlatformMediaPlayer * control
void setState(QMediaPlayer::PlaybackState state)
\qmltype MediaPlayer \nativetype QMediaPlayer
QList< QMediaMetaData > trackMetaData(QPlatformMediaPlayer::TrackType s) const
void setMedia(QUrl media, QIODevice *stream=nullptr)
void setStatus(QMediaPlayer::MediaStatus status)
Combined button and popup list for selecting options.