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

Question:

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)?

Asked By: clemsam lang

||

Answers:

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.

Answered By: mhsmith

Beeware provides access to android.media.MediaPlayer class.
Here something that worked for me

from android.media import MediaPlayer
mediaPlayer=MediaPlayer()
mediaPlayer.setDataSource("your_file_path")
mediaPlayer.prepare()
mediaPlayer.start()

Add to manifest permissions READ_EXTERNAL_STORAGE and READ_MEDIA_AUDIO
and give media permission in the phone settings

Answered By: user22546963