Search code examples
c++windowsqtcyrillicqmediaplayer

QMediaPlayer wrong parse url with cyrillic on Windows


I'm trying to play translation:

QString language = "ru";
QString text = "Привет мир";
QUrl preparedUrl = QUrl("http://translate.googleapis.com/translate_tts?ie=UTF-8&client=gtx&tl=" + language + "&q=" + text);
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(preparedUrl);
player->play();

On Windows this text playing "Знак опроса" for each symbol (this means "question mark" on English). This problems exists only with cyrillic. On Linux this code works fine.

What am I doing wrong? Is there a problem with the encoding?


Solution

  • As Evgeny mentioned, QString::fromUTF8 might help you, but only if you are using Qt4. In Qt5, QString(const char *) and QString::operator=(const char *) both already use QString::fromUTF8 (according to the documentation).

    I think your problem is the file encoding. Make sure your c++ source file is stored in UTF-8 encoding.

    There is also QString::fromLocal8Bit which might help you if you cannot store the file in UTF-8.


    Update: Tried that on Windows 7, does not work. Consider the below proof of concept for a working version. The #if 0 block should be identical to the #else one, but doen't work either. I would consider this a bug in the DirectShow backend. You might to try to get the WMF backed running, but I have never tried that.

        QUrl preparedUrl = QUrl("http://translate.googleapis.com/translate_tts?ie=UTF-8&client=gtx&tl=ru&q=%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82 %D0%BC%D0%B8%D1%80");
        QNetworkRequest request(preparedUrl);
    #if 0
        QMediaPlayer *player = new QMediaPlayer;
        player->setMedia(request);
        player->play();
    #else
        QNetworkAccessManager mgr;
        QNetworkReply * reply = mgr.get(request);
        QObject::connect(reply, &QNetworkReply::finished, [reply, preparedUrl]()
        {
            QByteArray * ba = new QByteArray(reply->readAll());
            QBuffer * buffer = new QBuffer(ba);
            buffer->open(QIODevice::ReadOnly);
            delete reply;
    
            QMediaPlayer *player = new QMediaPlayer;
            player->setMedia(preparedUrl, buffer);
            player->play();
        });
    #endif