pythonandroidcross-platformbeeware

How to play sound in an Android app created by BeeWare using Python?


I used the BeeWare environment to create a simple MahJong game (find & click pairs to remove them) using Python (with Toga as layout tool) for Android.

Now I would like to have some buttons give a "click sound" when pressed:

Anyone have a helping hint (or even working example)?


Solution

  • If you're using Briefcase 0.3.10 or newer (which uses Chaquopy to support Python on Android), then you could use the Chaquopy Python API to play audio files using SoundPool.

    For example, the code from this answer could be written in Python as follows:

    from android.media import AudioManager, SoundPool
    from os.path import dirname, join
    
    soundPool = SoundPool(5, AudioManager.STREAM_MUSIC, 0)
    soundId = soundPool.load(join(dirname(__file__), "filename.mp3"), 1)
    soundPool.play(soundId, 1, 1, 0, 0, 1)
    

    This will play the file "filename.mp3" from the same directory as the Python source file.