How to make a proxy working with QMediaPlayer in Q

2019-09-09 12:29发布

问题:

I have a little problem with my project on Qt. I am trying to play a web-radio directly with QMediaPlayer like this :

QMediaPlayer player;
player.setMedia(QUrl("http://listen.42fm.ru:8000/stealkill"));
player.play();

It works but another constraint I have is to setup an SSH tunneling (port 8000 is blocked on the network of deployment). So i set up my port forwarding on my device and I configured Qt proxy like this:

QNetworkProxy proxy;
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName("localhost");
proxy.setPort(1234);
QNetworkProxy::setApplicationProxy(proxy);

The proxy works for every HTTP request my application do, but it seems not working with QMediaPlayer (when I enter un bullshit proxy host name, my HTTP requests don't work anymore but QMediaPlayer still works...).

Any idea about setting up this correctly with QMediaPlayer ?

Thanks by advance for the help !

回答1:

You can try to create a request with proxy using QNetworkAccessManager mechanism and set QNetworkReply as a second parameter in QMediaPlayer::setMedia(const QMediaContent & media, QIODevice * stream = Q_NULLPTR). Check more info here.

There a short snippet:

QNetworkAccessManager * manager = new QNetworkAccessManager(this);

QNetworkProxy proxy;
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName("localhost");
proxy.setPort(1234);

manager -> setProxy(proxy);

QNetworkReply * reply = manager -> get(
  QNetworkRequest(
    QUrl("http://listen.42fm.ru:8000/stealkill")
  )
);

QMediaPlayer * player = new QMediaPlayer();
player -> setMedia(QMediaContent(), reply);
player.play();

Hope this will be helpful for you.