Reputation:
I want to play a music from QByteArray with so I can use it in many cases as to retrieve a sound from database or transfer it over network using Tcp etc..
So I use these lines of code
QFile file("E:\\amr.mp3"); // sound dir
file.open(QIODevice::ReadOnly);
QByteArray arr = file.readAll(); // change it to QbyteArray
QBuffer buffer(&arr);
qDebug() << "Buffer error = " << buffer.errorString(); // i get error from here "unkow error"
QMediaPlayer *player = new QMediaPlayer();
player->setMedia(QMediaContent(),&buffer);
player->play();
qDebug() << "Player error = " << player->errorString(); // no error ""
I see many solutions when I search, one of them is on stackoverflow the solution is to make a Qbuffer, pass to it the array and put it in setMedia but it didn't work so I need any help to make this code run or any other way to play a voice or music from QByteArray
Upvotes: 2
Views: 2503
Reputation: 8284
You just forgot to open the Buffer with
buffer.open(QIODevice::ReadOnly);
So a full working demo program is this:
#include <QApplication>
#include <QMediaPlayer>
#include <QFile>
#include <QBuffer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile file(R"(C:\test.mp3)"); // sound dir
file.open(QIODevice::ReadOnly);
QByteArray arr = file.readAll();
QMediaPlayer *player = new QMediaPlayer(&a);
QBuffer *buffer = new QBuffer(player);
buffer->setData(arr);
buffer->open(QIODevice::ReadOnly);
player->setMedia(QMediaContent(),buffer);
player->play();
return a.exec();
}
Upvotes: 5