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