I'm trying to play a couple of audio files stored in a QByteArray
object one after another. I've used a QBuffer
object to be able to play the audio using QMediaPlayer
.
It's successful to play the audio stored for the first time in the object, but when playing ends and the contents of another audio file gets stored in the object for the second time, the player can't play the audio well.
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QByteArray audio;
QBuffer buffer;
buffer.setBuffer(&audio);
QAudioOutput output;
QMediaPlayer player;
player.setAudioOutput(&output);
player.setSourceDevice(&buffer);
QFile file(":/audio/one.m4a");
qDebug() << (file.open(QFile::ReadOnly) ? "opened successfully." : "Failed to open.");
audio = file.readAll();
file.close();
buffer.open(QBuffer::ReadOnly);
player.play(); // plays one.m4a successfully.
QObject::connect(&player, &QMediaPlayer::playbackStateChanged, [&](QMediaPlayer::PlaybackState state)
{
if(state == QMediaPlayer::StoppedState) {
file.setFileName(":/audio/two.m4a");
qDebug() << (file.open(QFile::ReadOnly) ? "opened successfully." : "Failed to open.");
audio = file.readAll();
file.close();
player.play(); // fails to play two.m4a
}
});
return app.exec();
}
I just hear a beep-like sound effect as the player plays the second audio.
I created another QBuffer
object to represent the same QByteArray
object as the buffer. Anything else is similar. I just changed the source device of the player and this time, it can play the audio files successfully. That's why I think the problem comes from the QBuffer
object.
QBuffer one;
QObject::connect(&player, &QMediaPlayer::playbackStateChanged, [&](QMediaPlayer::PlaybackState state)
{
if(state == QMediaPlayer::StoppedState) {
one.setBuffer(&audio);
file.setFileName(":/audio/two.m4a");
qDebug() << (file.open(QFile::ReadOnly) ? "opened successfully." : "Failed to open.");
audio = file.readAll();
file.close();
one.open(QBuffer::ReadOnly);
player.setSourceDevice(&one);
player.play(); // plays two.m4a successfully.
}
});
return app.exec();
}