QMediaPlayer 类

QMediaPlayer class allows the playing of a media source. 更多...

Header: #include <QMediaPlayer>
qmake: QT += multimedia
继承: QMediaObject

公共类型

enum Error { NoError, ResourceError, FormatError, NetworkError, AccessDeniedError, ServiceMissingError }
enum Flag { LowLatency, StreamPlayback, VideoSurface }
flags Flags
enum MediaStatus { UnknownMediaStatus, NoMedia, LoadingMedia, LoadedMedia, ..., InvalidMedia }
enum State { StoppedState, PlayingState, PausedState }

特性

公共函数

QMediaPlayer (QObject * parent = nullptr, QMediaPlayer::Flags flags = Flags())
virtual ~QMediaPlayer ()
QAudio::Role audioRole () const
int bufferStatus () const
QMediaContent currentMedia () const
QNetworkConfiguration currentNetworkConfiguration () const
QString customAudioRole () const
qint64 duration () const
QMediaPlayer::Error error () const
QString errorString () const
bool isAudioAvailable () const
bool isMuted () const
bool isSeekable () const
bool isVideoAvailable () const
QMediaContent media () const
QMediaPlayer::MediaStatus mediaStatus () const
const QIODevice * mediaStream () const
qreal playbackRate () const
QMediaPlaylist * playlist () const
qint64 position () const
void setAudioRole (QAudio::Role audioRole )
void setCustomAudioRole (const QString & audioRole )
void setVideoOutput (QVideoWidget * output )
void setVideoOutput (QGraphicsVideoItem * output )
void setVideoOutput (QAbstractVideoSurface * surface )
QMediaPlayer::State state () const
QList<QAudio::Role> supportedAudioRoles () const
QStringList supportedCustomAudioRoles () const
int volume () const

重实现公共函数

virtual QMultimedia::AvailabilityStatus availability () const override

公共槽

void pause ()
void play ()
void setMedia (const QMediaContent & media , QIODevice * stream = nullptr)
void setMuted (bool muted )
void setNetworkConfigurations (const QList<QNetworkConfiguration> & configurations )
void setPlaybackRate (qreal rate )
void setPlaylist (QMediaPlaylist * playlist )
void setPosition (qint64 position )
void setVolume (int volume )
void stop ()

信号

void audioAvailableChanged (bool available )
void audioRoleChanged (QAudio::Role role )
void bufferStatusChanged (int percentFilled )
void currentMediaChanged (const QMediaContent & media )
void customAudioRoleChanged (const QString & role )
void durationChanged (qint64 duration )
void error (QMediaPlayer::Error error )
void mediaChanged (const QMediaContent & media )
void mediaStatusChanged (QMediaPlayer::MediaStatus status )
void mutedChanged (bool muted )
void networkConfigurationChanged (const QNetworkConfiguration & configuration )
void playbackRateChanged (qreal rate )
void positionChanged (qint64 position )
void seekableChanged (bool seekable )
void stateChanged (QMediaPlayer::State state )
void videoAvailableChanged (bool videoAvailable )
void volumeChanged (int volume )

静态公共成员

QMultimedia::SupportEstimate hasSupport (const QString & mimeType , const QStringList & codecs = QStringList(), QMediaPlayer::Flags flags = Flags())
const QMetaObject staticMetaObject

额外继承成员

详细描述

QMediaPlayer class allows the playing of a media source.

QMediaPlayer class is a high level media playback class. It can be used to playback such content as songs, movies and internet radio. The content to playback is specified as a QMediaContent object, which can be thought of as a main or canonical URL with additional information attached. When provided with a QMediaContent playback may be able to commence.

player = new QMediaPlayer;
connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
player->setMedia(QUrl::fromLocalFile("/Users/me/Music/coolsong.mp3"));
player->setVolume(50);
player->play();
							

QVideoWidget can be used with QMediaPlayer for video rendering and QMediaPlaylist for accessing playlist functionality.

playlist = new QMediaPlaylist;
playlist->addMedia(QUrl("http://example.com/movie1.mp4"));
playlist->addMedia(QUrl("http://example.com/movie2.mp4"));
playlist->addMedia(QUrl("http://example.com/movie3.mp4"));
playlist->setCurrentIndex(1);
player = new QMediaPlayer;
player->setPlaylist(playlist);
videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);
videoWidget->show();
player->play();
							

Since QMediaPlayer QMediaObject , you can use several of the QMediaObject functions for things like:

另请参阅 QMediaObject , QMediaService , QVideoWidget ,和 QMediaPlaylist .

成员类型文档编制

enum QMediaPlayer:: Error

Defines a media player error condition.

常量 描述
QMediaPlayer::NoError 0 No error has occurred.
QMediaPlayer::ResourceError 1 A media resource couldn't be resolved.
QMediaPlayer::FormatError 2 The format of a media resource isn't (fully) supported. Playback may still be possible, but without an audio or video component.
QMediaPlayer::NetworkError 3 A network error occurred.
QMediaPlayer::AccessDeniedError 4 There are not the appropriate permissions to play a media resource.
QMediaPlayer::ServiceMissingError 5 A valid playback service was not found, playback cannot proceed.

enum QMediaPlayer:: Flag
flags QMediaPlayer:: Flags

常量 描述
QMediaPlayer::LowLatency 0x01 The player is expected to be used with simple audio formats, but playback should start without significant delay. Such playback service can be used for beeps, ringtones, etc.
QMediaPlayer::StreamPlayback 0x02 The player is expected to play QIODevice based streams. If passed to QMediaPlayer constructor, the service supporting streams playback will be chosen.
QMediaPlayer::VideoSurface 0x04 The player is expected to be able to render to a QAbstractVideoSurface output .

Flags 类型是 typedef 对于 QFlags <Flag>。它存储 Flag 值的 OR 组合。

enum QMediaPlayer:: MediaStatus

Defines the status of a media player's current media.

常量 描述
QMediaPlayer::UnknownMediaStatus 0 The status of the media cannot be determined.
QMediaPlayer::NoMedia 1 The is no current media. The player is in the StoppedState .
QMediaPlayer::LoadingMedia 2 The current media is being loaded. The player may be in any state.
QMediaPlayer::LoadedMedia 3 The current media has been loaded. The player is in the StoppedState .
QMediaPlayer::StalledMedia 4 Playback of the current media has stalled due to insufficient buffering or some other temporary interruption. The player is in the PlayingState or PausedState .
QMediaPlayer::BufferingMedia 5 The player is buffering data but has enough data buffered for playback to continue for the immediate future. The player is in the PlayingState or PausedState .
QMediaPlayer::BufferedMedia 6 The player has fully buffered the current media. The player is in the PlayingState or PausedState .
QMediaPlayer::EndOfMedia 7 Playback has reached the end of the current media. The player is in the StoppedState .
QMediaPlayer::InvalidMedia 8 The current media cannot be played. The player is in the StoppedState .

enum QMediaPlayer:: State

定义媒体播放器的当前状态。

常量 描述
QMediaPlayer::StoppedState 0 媒体播放器未播放内容,回放将从当前轨道的起始开始。
QMediaPlayer::PlayingState 1 媒体播放器目前正在播放内容。
QMediaPlayer::PausedState 2 媒体播放器已暂停回放,当前轨道的回放将从播放器暂停位置处再继续。

特性文档编制

audioAvailable : const bool

This property holds the audio availabilty status for the current media.

As the life time of QMediaPlayer can be longer than the playback of one QMediaContent , this property may change over time, the audioAvailableChanged signal can be used to monitor it's status.

访问函数:

bool isAudioAvailable () const

通知信号:

void audioAvailableChanged (bool available )

audioRole : QAudio::Role

This property holds the role of the audio stream played by the media player.

It can be set to specify the type of audio being played, allowing the system to make appropriate decisions when it comes to volume, routing or post-processing.

The audio role must be set before calling setMedia ().

customAudioRole is cleared when this property is set to anything other than QAudio::CustomRole .

This property was introduced in Qt 5.6.

访问函数:

QAudio::Role audioRole () const
void setAudioRole (QAudio::Role audioRole )

通知信号:

void audioRoleChanged (QAudio::Role role )

另请参阅 supportedAudioRoles ().

bufferStatus : const int

This property holds the percentage of the temporary buffer filled before playback begins or resumes, from 0 (empty) to 100 (full).

When the player object is buffering; this property holds the percentage of the temporary buffer that is filled. The buffer will need to reach 100% filled before playback can start or resume, at which time mediaStatus () 会返回 BufferedMedia or BufferingMedia . If the value is anything lower than 100 , mediaStatus () 会返回 StalledMedia .

访问函数:

int bufferStatus () const

通知信号:

void bufferStatusChanged (int percentFilled )

另请参阅 mediaStatus ().

currentMedia : const QMediaContent

This property holds the current active media content being played by the player object. This value could be different from QMediaPlayer::media property if a playlist is used. In this case currentMedia indicates the current media content being processed by the player, while QMediaPlayer::media property contains the original playlist.

访问函数:

QMediaContent currentMedia () const

通知信号:

void currentMediaChanged (const QMediaContent & media )

另请参阅 QMediaContent and media ().

customAudioRole : QString

This property holds the role of the audio stream played by the media player.

It can be set to specify the type of audio being played when the backend supports audio roles unknown to Qt. Specifying a role allows the system to make appropriate decisions when it comes to volume, routing or post-processing.

The audio role must be set before calling setMedia ().

audioRole is set to QAudio::CustomRole when this property is set.

This property was introduced in Qt 5.11.

访问函数:

QString customAudioRole () const
void setCustomAudioRole (const QString & audioRole )

通知信号:

void customAudioRoleChanged (const QString & role )

另请参阅 supportedCustomAudioRoles ().

duration : const qint64

This property holds the duration of the current media.

The value is the total playback time in milliseconds of the current media. The value may change across the life time of the QMediaPlayer object and may not be available when initial playback begins, connect to the durationChanged () signal to receive status notifications.

访问函数:

qint64 duration () const

通知信号:

void durationChanged (qint64 duration )

error : const QString

This property holds a string describing the last error condition.

访问函数:

QString errorString () const

另请参阅 error ().

media : QMediaContent

This property holds the active media source being used by the player object.

The player object will use the QMediaContent for selection of the content to be played.

By default this property has a null QMediaContent .

Setting this property to a null QMediaContent will cause the player to discard all information relating to the current media source and to cease all I/O operations related to that media.

访问函数:

QMediaContent media () const
void setMedia (const QMediaContent & media , QIODevice * stream = nullptr)

通知信号:

void mediaChanged (const QMediaContent & media )

另请参阅 QMediaContent and currentMedia ().

mediaStatus : const MediaStatus

This property holds the status of the current media stream.

The stream status describes how the playback of the current stream is progressing.

默认情况下,此特性为 QMediaPlayer::NoMedia

访问函数:

QMediaPlayer::MediaStatus mediaStatus () const

通知信号:

void mediaStatusChanged (QMediaPlayer::MediaStatus status )

另请参阅 state .

muted : bool

This property holds the muted state of the current media.

The value will be true if the playback volume is muted; otherwise false.

访问函数:

bool isMuted () const
void setMuted (bool muted )

通知信号:

void mutedChanged (bool muted )

playbackRate : qreal

This property holds the playback rate of the current media.

This value is a multiplier applied to the media's standard play rate. By default this value is 1.0, indicating that the media is playing at the standard pace. Values higher than 1.0 will increase the rate of play. Values less than zero can be set and indicate the media will rewind at the multiplier of the standard pace.

Not all playback services support change of the playback rate. It is framework defined as to the status and quality of audio and video while fast forwarding or rewinding.

访问函数:

qreal playbackRate () const
void setPlaybackRate (qreal rate )

通知信号:

void playbackRateChanged (qreal rate )

playlist : QMediaPlaylist *

This property holds the media playlist being used by the player object.

The player object will use the current playlist item for selection of the content to be played.

By default this property is set to null.

If the media playlist is used as a source, QMediaPlayer::currentMedia is updated with a current playlist item. The current source should be selected with QMediaPlaylist::setCurrentIndex (int) instead of QMediaPlayer::setMedia (), otherwise the current playlist will be discarded.

访问函数:

QMediaPlaylist * playlist () const
void setPlaylist (QMediaPlaylist * playlist )

另请参阅 QMediaContent .

position : qint64

This property holds the playback position of the current media.

The value is the current playback position, expressed in milliseconds since the beginning of the media. Periodically changes in the position will be indicated with the signal positionChanged (), the interval between updates can be set with QMediaObject 's method setNotifyInterval ().

访问函数:

qint64 position () const
void setPosition (qint64 position )

通知信号:

void positionChanged (qint64 position )

seekable : const bool

This property holds the seek-able status of the current media

If seeking is supported this property will be true; false otherwise. The status of this property may change across the life time of the QMediaPlayer object, use the seekableChanged signal to monitor changes.

访问函数:

bool isSeekable () const

通知信号:

void seekableChanged (bool seekable )

state : const State

此特性保持媒体播放器的回放状态。

默认情况下,此特性为 QMediaPlayer::Stopped

访问函数:

QMediaPlayer::State state () const

通知信号:

void stateChanged (QMediaPlayer::State state )

另请参阅 mediaStatus (), play (), pause (),和 stop ().

videoAvailable : const bool

This property holds the video availability status for the current media.

If available, the QVideoWidget class can be used to view the video. As the life time of QMediaPlayer can be longer than the playback of one QMediaContent , this property may change over time, the videoAvailableChanged signal can be used to monitor it's status.

访问函数:

bool isVideoAvailable () const

通知信号:

void videoAvailableChanged (bool videoAvailable )

另请参阅 QVideoWidget and QMediaContent .

volume : int

This property holds the current playback volume.

The playback volume is scaled linearly, ranging from 0 (silence) to 100 (full volume). Values outside this range will be clamped.

By default the volume is 100 .

UI volume controls should usually be scaled nonlinearly. For example, using a logarithmic scale will produce linear changes in perceived loudness, which is what a user would normally expect from a volume control. See QAudio::convertVolume () 了解更多细节。

访问函数:

int volume () const
void setVolume (int volume )

通知信号:

void volumeChanged (int volume )

成员函数文档编制

QMediaPlayer:: QMediaPlayer ( QObject * parent = nullptr, QMediaPlayer::Flags flags = Flags())

Construct a QMediaPlayer instance parented to parent and with flags .

[virtual] QMediaPlayer:: ~QMediaPlayer ()

Destroys the player object.

[signal] void QMediaPlayer:: audioAvailableChanged ( bool available )

Signals the availability of audio content has changed to available .

注意: 通知信号为特性 audioAvailable .

[signal] void QMediaPlayer:: audioRoleChanged ( QAudio::Role role )

Signals that the audio role of the media player has changed.

This function was introduced in Qt 5.6.

注意: 通知信号为特性 audioRole .

[override virtual] QMultimedia::AvailabilityStatus QMediaPlayer:: availability () const

Reimplemented from QMediaObject::availability ().

[signal] void QMediaPlayer:: bufferStatusChanged ( int percentFilled )

Signal the amount of the local buffer filled as a percentage by percentFilled .

注意: 通知信号为特性 bufferStatus .

[signal] void QMediaPlayer:: currentMediaChanged (const QMediaContent & media )

Signals that the current playing content has been changed to media .

注意: 通知信号为特性 currentMedia .

另请参阅 currentMedia () 和 mediaChanged ().

QNetworkConfiguration QMediaPlayer:: currentNetworkConfiguration () const

Returns the current network access point in use. If a default contructed QNetworkConfiguration is returned this feature is not available or that none of the current supplied configurations are in use.

[signal] void QMediaPlayer:: customAudioRoleChanged (const QString & role )

Signals that the audio role of the media player has changed.

This function was introduced in Qt 5.11.

注意: 通知信号为特性 customAudioRole .

[signal] void QMediaPlayer:: durationChanged ( qint64 duration )

Signal the duration of the content has changed to duration , expressed in milliseconds.

注意: 通知信号为特性 duration .

QMediaPlayer::Error QMediaPlayer:: error () const

Returns the current error state.

[signal] void QMediaPlayer:: error ( QMediaPlayer::Error error )

Signals that an error condition has occurred.

注意: Signal error 在此类中被重载。通过使用函数指针句法连接到此信号,Qt 提供用于获得如此范例展示的函数指针的方便帮助程序:

connect(mediaPlayer, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
    [=](QMediaPlayer::Error error){ /* ... */ });
							

另请参阅 errorString ().

[static] QMultimedia::SupportEstimate QMediaPlayer:: hasSupport (const QString & mimeType , const QStringList & codecs = QStringList(), QMediaPlayer::Flags flags = Flags())

Returns the level of support a media player has for a mimeType and a set of codecs .

flags argument allows additional requirements such as performance indicators to be specified.

[signal] void QMediaPlayer:: mediaChanged (const QMediaContent & media )

Signals that the media source has been changed to media .

注意: 通知信号为特性 media .

另请参阅 media () 和 currentMediaChanged ().

[signal] void QMediaPlayer:: mediaStatusChanged ( QMediaPlayer::MediaStatus status )

Signals that the status of the current media has changed.

注意: 通知信号为特性 mediaStatus .

另请参阅 mediaStatus ().

const QIODevice *QMediaPlayer:: mediaStream () const

Returns the stream source of media data.

This is only valid if a stream was passed to setMedia ().

另请参阅 setMedia ().

[signal] void QMediaPlayer:: mutedChanged ( bool muted )

Signal the mute state has changed to muted .

注意: 通知信号为特性 muted .

[signal] void QMediaPlayer:: networkConfigurationChanged (const QNetworkConfiguration & configuration )

Signal that the active in use network access point has been changed to configuration and all subsequent network access will use this configuration .

[slot] void QMediaPlayer:: pause ()

Pause playing the current source.

[slot] void QMediaPlayer:: play ()

Start or resume playing the current source.

[signal] void QMediaPlayer:: playbackRateChanged ( qreal rate )

Signals the playbackRate has changed to rate .

注意: 通知信号为特性 playbackRate .

[signal] void QMediaPlayer:: positionChanged ( qint64 position )

Signal the position of the content has changed to position , expressed in milliseconds.

注意: 通知信号为特性 position .

[signal] void QMediaPlayer:: seekableChanged ( bool seekable )

Signals the seekable status of the player object has changed.

注意: 通知信号为特性 seekable .

[slot] void QMediaPlayer:: setMedia (const QMediaContent & media , QIODevice * stream = nullptr)

Sets the current media source.

stream is supplied; media data will be read from it instead of resolving the media source. In this case the media source may still be used to resolve additional information about the media such as mime type. The stream must be open and readable.

Setting the media to a null QMediaContent will cause the player to discard all information relating to the current media source and to cease all I/O operations related to that media.

注意: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors. Listen for the mediaStatusChanged () 和 error () signals to be notified when the media is loaded and when an error occurs during loading.

Since Qt 5.12.2, the url scheme gst-pipeline provides custom pipelines for the GStreamer backend.

player = new QMediaPlayer;
player->setMedia(QUrl("gst-pipeline: videotestsrc ! autovideosink"));
player->play();
							

If the pipeline contains a video sink element named qtvideosink , current QVideoWidget can be used to render the video.

If the pipeline contains appsrc element, it will be used to push data from stream .

QImage img("images/qt-logo.png");
img = img.convertToFormat(QImage::Format_ARGB32);
QByteArray ba(reinterpret_cast<const char *>(img.bits()), img.sizeInBytes());
QBuffer buffer(&ba);
buffer.open(QIODevice::ReadOnly);
player = new QMediaPlayer;
player->setMedia(QUrl("gst-pipeline: appsrc blocksize=4294967295 ! \
    video/x-raw,format=BGRx,framerate=30/1,width=200,height=147 ! \
    coloreffects preset=heat ! videoconvert ! video/x-raw,format=I420 ! jpegenc ! rtpjpegpay ! \
    udpsink host=127.0.0.1 port=5000"), &buffer);
player->play();
QMediaPlayer *receiver = new QMediaPlayer;
videoWidget = new QVideoWidget;
receiver->setVideoOutput(videoWidget);
receiver->setMedia(QUrl("gst-pipeline: udpsrc port=5000 ! \
    application/x-rtp,encoding-name=JPEG,payload=26 ! rtpjpegdepay ! jpegdec ! \
    xvimagesink name=qtvideosink"));
receiver->play();
// Content will be shown in this widget.
videoWidget->show();
							

注意: Setter 函数为特性 media .

另请参阅 media ().

[slot] void QMediaPlayer:: setNetworkConfigurations (const QList < QNetworkConfiguration > & configurations )

Sets the network access points for remote media playback. configurations contains, in ascending preferential order, a list of configuration that can be used for network access.

This will invalidate the choice of previous configurations.

void QMediaPlayer:: setVideoOutput ( QVideoWidget * output )

Attach a QVideoWidget video output to the media player.

If the media player has already video output attached, it will be replaced with a new one.

void QMediaPlayer:: setVideoOutput ( QGraphicsVideoItem * output )

Attach a QGraphicsVideoItem video output to the media player.

If the media player has already video output attached, it will be replaced with a new one.

void QMediaPlayer:: setVideoOutput ( QAbstractVideoSurface * surface )

Sets a video surface as the video output of a media player.

If a video output has already been set on the media player the new surface will replace it.

[signal] void QMediaPlayer:: stateChanged ( QMediaPlayer::State state )

Signal the state of the Player object has changed.

注意: 通知信号为特性 state .

[slot] void QMediaPlayer:: stop ()

Stop playing, and reset the play position to the beginning.

QList < QAudio::Role > QMediaPlayer:: supportedAudioRoles () const

Returns a list of supported audio roles.

If setting the audio role is not supported, an empty list is returned.

This function was introduced in Qt 5.6.

另请参阅 audioRole .

QStringList QMediaPlayer:: supportedCustomAudioRoles () const

Returns a list of supported custom audio roles. An empty list may indicate that the supported custom audio roles aren't known. The list may not be complete.

This function was introduced in Qt 5.11.

另请参阅 customAudioRole .

[signal] void QMediaPlayer:: videoAvailableChanged ( bool videoAvailable )

Signal the availability of visual content has changed to videoAvailable .

注意: 通知信号为特性 videoAvailable .

[signal] void QMediaPlayer:: volumeChanged ( int volume )

Signal the playback volume has changed to volume .

注意: 通知信号为特性 volume .