Case 1. I managed to play a sound with QMediaPlayer like this:
QMediaPlayer* media = new QMediaPlayer();
media->setMedia("sound.mp3");
media->play();
Case 2. Everything is ok also if I load the sound into memory and play it like this:
QFile file("sound.mp3");
file.open(QIODevice::ReadOnly);
QByteArray* arr = new QByteArray(file.readAll());
file.close();
QBuffer* buffer = new QBuffer(arr);
buffer->open(QIODevice::ReadOnly);
buffer->seek(0);
QMediaPlayer* media = new QMediaPlayer();
media->setMedia(QMediaContent(), buffer);
media->play();
The problem is when I try to play a file that is not a real sound like file.txt
.
In first case the player stops immediately.
In the second case the player remains in state PlayingState
(QMediaPlayer::BufferedMedia
, QMediaPlayer::NoError
)
Documentation:
void QMediaPlayer::setMedia(const QMediaContent &media, QIODevice *stream = Q_NULLPTR)
Sets the current media source.
If a 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.
So, if I use media->setMedia(QMediaContent(), buffer);
then the mediaplayer will read data from memory without additional information as mime type because of null QMediaContent. Maybe mediaplayer remain in PlayingState because of lack of mime type, trying to play a text file loaded in memory.
So I try to use a valid QMediaContent in conjunction with the loaded data... the same result: mediaplayer remain in PlayingState without any error.
media->setMedia(QMediaContent(QUrl::fromLocalFile(QFileInfo(s).absoluteFilePath())), buffer);
How can I play a sound loaded into memory with QMediaPlayer avoiding this issue?