Qt World Summit: Register Today!

Problem with QMediaPlayer

  • Hi, i have big problem with QMEdiaPlayer.
    I wanna do simple thing, just to play the sound when the button is clicked, but if i use a Non - Dynamically allocated memory, then it's gonna do some weird noise, and restart from beginning.

    If i use this code:

    #include <QMediaPlayer>;
    QMediaPlayer* play_sound;
    void Play_Sound()
    play_sound= new QMediaPlayer;
    delete play_sound;

    I tried with QMediaState::EndOfMedia, but it does nothing.

    Then if i dont delete it, it's working, but at some point it's gonna allocate so much memory, if I delete it, their is no sound, null..

    I tried in many many ways, i tried to use static members, but nothing works.
    It has the wanted effect, only when i use it with new, but then if i delete it, like i said, their is no sound.

    I tryied with QSound too, but it give me just some errors like "Unable to encoding"
    i tried with .mp3 or .wav, should work, because i read it, but it doesn't.
    Any help here? No clue what to do with that.

  • Try to define QMediaPlayer* play_sound; outside the function Play_Sound().
    Maybe the file is still on run when you delete the object.

  • I think i tried it, and it doesn't work. If i new it outside, and delete, it's gonna crash after second click, because the object is deleted. Even if i use a static member in this way, it won't work how i wanted it.

  • Lifetime Qt Champion

    Hi @Loc888,

    Have you already looked at the QMediaPlayer example?

    It's a bigger one, but I was able to run it on my computer without problems.


  • @aha_1980
    Probably their is nothing about "delete", i don't know why ther is no sound if i put "delete"
    at the end. If i dont do that, then the memory it's gonna end at some point, if i do that, ther is no sound...

    My goal is to achieve, when someone press the button two or more times, the sound is gonna be played that many times, and it's not gonna re-start from the beginning.

  • Lifetime Qt Champion


    You are using a static pointer to your QMediaPlayer that you are re-allocating each time you call that function. That’s the first problem. Second is that play is not a blocking call so calling delete right after play will immediately delete the QMediaPlayer object likely before it can start playing.

    You should have a better encapsulation of that functionality so that you don’t reallocate every time but just start playing the sound.

Log in to reply