| Android code examples to play audio asset or resource files.
[ Dec-2019 ] |
Source code | audiodemo-src.zip |
Mp3 sample files (copyright unknown) | audio-mp3.zip |
Android APK (min API 19, target 29) zip'd | audiodemo-apk.zip |
Android APK (min API 19, target 29) | audiodemo.apk |
WARNING - Chrome on 4.2 will get stuck trying to download APK, use a different browser like FireFox | |
GitHub source | https://github.com/landenlabs/all_AudioDemo |
Simple applications with list of audio files. The audio files are stored in botht the res/raw directory and the asset directory. Best to stored audio files in mp3 encoding audio format which is supported by both old and new OS levels.
Android media formats
Image shows workspace layout with audio files (mp3) stored in both assets and res/raw directory.
Select and audio file then press the various play otions:
Raw - Play audio file stored in res/raw directory Asset - Play audio file stored in asset directory Network - Play audio files stored remotely Notification FG - Play using status notification service in foreground Notification BG - Play using status notification service in background
/** * Play sound file stored in res/raw/ directory */ private void playRawSound(String rawName) { try { // Two ways to provide resource, either using its name or resource id. // // Name // Syntax : android.resource://[package]/[res type]/[res name] // Example : Uri.parse("android.resource://com.my.package/raw/sound1"); // // Resource id // Syntax : android.resource://[package]/[resource_id] // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1); String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; String path; if (false) { // Build path using resource name path = RESOURCE_PATH + getPackageName() + "/raw/" + rawName; } else { // Build path using resource number int resID = getResources().getIdentifier(rawName, "raw", getPackageName()); path = RESOURCE_PATH + getPackageName() + File.separator + resID; } Uri soundUri = Uri.parse(path); mSoundName.setText(path); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setVolume(1.0f, 1.0f); mMediaPlayer.setLooping(false); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { Toast.makeText(getApplicationContext(), "start playing sound", Toast.LENGTH_SHORT).show(); mMediaPlayer.start(); } }); mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Toast.makeText(getApplicationContext(), String.format(Locale.US, "Media error what=%d extra=%d", what, extra), Toast.LENGTH_LONG).show(); return false; } }); // // Different ways to load audio into player: // 1. Using path to resource by name or by id // 2. Using content provider to load audio and passing a file descriptor. if (true) { // 1. open audio using path to data inside package mMediaPlayer.setDataSource(getApplicationContext(), soundUri); mMediaPlayer.prepare(); } else { // 2. Load using content provider, passing file descriptor. ContentResolver resolver = getContentResolver(); AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r"); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.prepareAsync(); } // See setOnPreparedListener above // mMediaPlayer.start(); } catch (Exception ex) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }
/** * Play sound file stored in assets/sounds/ directory. */ private void playAssetSound(String assetName) { try { AssetFileDescriptor afd = getAssets().openFd("sounds/" + assetName + ".mp3"); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (Exception ex) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }
Example of how to play Audio file found remotely using network access. Before you can complete the remote nework access you have to enable network permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
If your access is using HTTP you need to also enable ClearText.
https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permittedAlso review supported file formats:
https://developer.android.com/guide/topics/media/media-formats
Sample code to load network mp3.
/**
* Play sound file from remote location.
* Accessing external data not found inside package. SD card or network.
* "/sdcard/sample.mp3";
* "http://www.bogotobogo.com/Audio/sample.mp3";
*
* May require settings in AndroidManifest to enable ClearText and internet permission.
*
* See supported file formats
* https://developer.android.com/guide/topics/media/media-formats
* See enable cleartext if network path is using http. Not required for https
* https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
* Add network permission to AndroidManifest.xml
*
*/
private void playNetworkSound(String netUrl) {
try {
mSoundName.setText(netUrl);
mMediaPlayer = new MediaPlayer();
// mMediaPlayer.setVolume(1.0f, 1.0f);
mMediaPlayer.setLooping(false);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Toast.makeText(getApplicationContext(),
"start playing sound", Toast.LENGTH_SHORT).show();
mMediaPlayer.start();
}
});
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), String.format(Locale.US,
"Media error what=%d extra=%d", what, extra), Toast.LENGTH_LONG).show();
return false;
}
});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(netUrl);
mMediaPlayer.prepareAsync(); // Use prepareAsync for external sources.
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
Example of how to play Audio file in resource raw directory using the Status bar Notifcation service:
private void notifySound(String assetName) {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
String path;
if (false) {
path = RESOURCE_PATH + getPackageName() + "/raw/" + assetName;
} else {
int resID = getResources().getIdentifier(assetName, "raw", getPackageName());
path = RESOURCE_PATH + getPackageName() + File.separator + resID;
}
Uri soundUri = Uri.parse(path);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(soundUri); //This sets the sound to play
notificationManager.notify(10, mBuilder.build());
}
Example of how to play Audio file in resource raw directory using the Status bar Notifcation service in the background. The code uses the same notification code, but first moves the acivity to the back of the stack and moves the home screen to the front. The code also includes buttons in the notification bar to replay the sound.
/**
* Play sound in background:
* 1. Move activity to back of stack
* 2. Bring home page of device into view.
* 3. Sleep for 2 seconds to make sure we are in background.
* 4. Play sound using notification, update notification msg.
*/
private void notifySoundBg(String assetName) {
// JobScheduler
boolean sentAppToBackground = moveTaskToBack(true);
if (!sentAppToBackground){
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
new Handler().postDelayed (() -> {
notifySound(getApplicationContext(), assetName, NotifyUtil.getIsForeground(mSoundName));
}, 2000);
}
Currently both the Replay and the Next buttons on the Notification draw will execute the same Intent and is currently wire to replay the current sound file.
Syntax code highligter provided by https://highlightjs.org