Just Play my Sound
When you start developing a new App, you usually put a lot of effort into the app's core functionality and, of course, into a nice design to keep your users happy. But there's not always spare time to invest on adding sounds to it too. So, here we are to help you out!
To play a sound in Android, the dev should be aware of an important class: MediaPlayer.
This class, in combination with AudioManager, has all the tools required to manage and play sounds in Android. You can check them at the Android Developer Official Website where you will find the required knowledge.
But even then, even with such a nice tutorial, the dev won't be able to escape from:
- Managing the
MediaPlayerlife cycle, including setting the proper media source.
- Creating a task every time you need an async reproduction.
So, what could we possibly have done to solve this? Think about it...yes, you almost have it...a bit more...YES, YOU GOT IT MAN!
We developed a simple wrapper to handle both issues that even leaves the media source input divided into three equally named methods through polymorphism.
This, is JustPlay: a simple sound player manager wrapper.
It currently supports three media sources:
- RAW: Local stored raw files
- URI: URI pointing to audio files, regardless of their origin.
- URL: Directly stream a audio file and play it.
Whenever you need to play a sound, you will only have to call first the library (with the sound source in any of the formats), and then the library method 'thisAudio' with both the desired sound and app context as parameters.
Accessing the audio source
This step depends on the type of your source:
- The RAW files, that you save in the
res/rawfolder, can be accessed through the
Rgenerated class in this way:
R.raw.sound, returning the associated
- The URLs can be sent just as a regular
- The internal URIs formatted in the
URIclass, such as one you might obtain from a Content Resolver. For example:
Uri.parse("android.resource" + "://" + getPackageName() + "/raw/sound");
Play the sound
As the library suggest, this step is a piece of cake:
- If you try to play the same sound repeatedly, or different files together, it will work as expected.
- It initiates a new task per sound.
This library gives you a simpler approach to the problematic, but at the same time you lose control over the reproduction.
That's all! Easy and short, ideal for those who want to play a few user event-related sounds in their app without adding complexity to the code... besides that, it's nice to read
JustPlay.thisSound(source, context); inside your code!