Important: Please read the Qt Code of Conduct -

How to add sound when window opens?

  • I've tried making it so that the sound will start when the window before it closes by pushing a button but it really doesn't work at all. I just want to find out how to autoplay a mp3 file. I have no clue how to do so. Can anyone help?

  • Maybe QSound?

    But it has some limitation, such that it can't play a sound file you include into your app as resource.

    Therefore I tend to use PlaySound() directly, on Win32.

  • I'm on a mac so I can't use any functions strictly for windows. Plus I'd prefer if I could keep this cross-platform. I tried QSound and used the code
    @ QSound music("/sound/08 West Mansion.mp3");;@

    However that didn't work quite right. It makes no sound when I press the button that it should be associated with.

  • The QSound documentation says:

    bq. Mac OS X: NSSound is used. All formats that NSSound supports, including QuickTime formats, are supported by Qt for Mac OS X.

    So I think on Mac OS X playing MP3 files should work. But maybe AAC/MP4 would be more common these days. This is in contrast to Windows, where only WAVE files are supported by QSound.

  • Well I'm working with my friend on this so I need it to be completely os independent cause he's on a pc. Unless maybe I make two seperate blocks of code? One for mac and one for pc. Giving each its own code respectively. Now I'm kinda just bouncing ideas off of you. Would you mind showing me how you'd do this with PlaySound()?

  • Using PlaySound is straight forward:
    @#include <Windows.h>
    #include <MMSystem.h>

    Here IDR_WAVE_FOO is the Resource Id of the Wave file we want to play. But this refers to Win32 resources, which are completely separate from Qt's resource system. But both can be used in the same binary just fine.

    But if you rneed something that really works platfrom-independant, you might call MPlayer as an external process via QProcess. You need a separate MPlayer binary for each platfrom, but that shouldn't be a problem...

Log in to reply