2

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

1 Answers1

5

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();
}
PeterT
  • 7,981
  • 1
  • 26
  • 34
  • 1
    first thanks for your replay,it works fine in The main, but when i use it on push_button clicked i get crash when press a button i can edite in the question –  Jun 28 '16 at 18:42
  • 2
    @hello you need to make sure that the ByteArray and QBuffer survives your function, so you would have to do `QByteArray *arr = new QByteArray(file.readAll()); QBuffer *buffer = new QBuffer(arr);` (potentially pass the QMediaPlayer as the parent or manage lifetime yourself). But none of this is relevant to your original question – PeterT Jun 28 '16 at 18:54
  • 1
    Calling an `errorString` method on anything in Qt without verifying that there's an error to begin with is pointless and may lead to wrong conclusions. A `QBuffer` has no `error()` method and no way of reporting errors at all, so calling its `errorString()` is always wrong. A `QMediaPlayer`'s `error()` must be checked first, and only if there is an error should you call `errorString()` and emit debug output. – Kuba hasn't forgotten Monica Jun 28 '16 at 21:17