- Android examples how to play audio files
- Play audio file from resource raw directory
- Play audio file from asset directory
- Play mp3 from network source
- Play using Notification service in foreground
- Play using Notification service in background
- Программирование звука в Android — SoundPool и MediaPlayer
- Android управление звуком
- Как проиграть звук через SoundPool
- SoundPool и утечка памяти
- Воспроизведение фоновой музыки в Android с помощью MediaPlayer
- Building a simple audio app in Android (Part 2/3)
- Building the app
- Introduction
- Part 2/3 — Building the app
- What does the app look like?
- Where is the source code?
- googlesamples/android-SimpleMediaPlayer
- Contribute to android-SimpleMediaPlayer development by creating an account on GitHub.
- Building the app
- Loading Media (prepare, prepareAsync)
- Playback controls (start, reset, stop, seekTo)
- MediaPlayer lifecycle
- Building a simple audio app in Android (Part 1/3)
- MediaPlayer introduction
- Introduction
- Part 1/3 — MediaPlayer introduction
- Basic MediaPlayer tasks
- Simplified state machine
Android examples how to play audio files
[ Dec-2019 ]
Download [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.
Image shows workspace layout with audio files (mp3) stored in both assets and res/raw directory.
Sample of Audio Demo app screen:
Select and audio file then press the various play otions:
Play audio file from resource raw directory
Play audio file from asset directory
Play mp3 from network source
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
If your access is using HTTP you need to also enable ClearText.
Sample code to load network mp3.
Play using Notification service in foreground
Example of how to play Audio file in resource raw directory using the Status bar Notifcation service:
Play using Notification service in background
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.
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.
Источник
Программирование звука в Android — SoundPool и MediaPlayer
Перед любым разработчиком, занимающимся созданием красивых интерактивных приложений, рано или поздно встает вопрос об использовании мультимедийных возможностей телефона. Для работы со звуком в Android программисты активно используют две библиотеки. Первая из них предоставляет класс SoundPool, вторая — MediaPlayer.
Класс SoundPool удобно использовать для проигрывания коротких аудиоклипов. С его помощью можно проигрывать несколько звуков одновременно, при этом размер звукового файла не должен превышать 1 Mb. Класс MediaPlayer лучше подходит для воспроизведения долгих аудио и видеороликов.
Android управление звуком
Android поддерживает различные аудиопотоки для разных целей. Регулятор расположенная на торце телефона качелька для регулирования громкости управляет только одним аудиопотоком. Для того, чтобы привязать эту кнопку к аудиопотоку необходимо указать его тип в приложении
Как проиграть звук через SoundPool
Напишем приложение, которое будет проигрывать звук при касании экрана. Создадим новый проект с именем CrazySong, пакет назовем
ru.mobilab.crazysong, в качестве главной Activity укажем CrazySongActivity.
Приведем main.xml к виду
Давайте рассмотрим последовательность действий, которую необходимо выполнить для того, чтобы воспроизвести звуковой файл. Прежде всего мы должны создать объект soundPool. Его конструктор имеет несколько параметров. Первый параметр задает максимальное число одновременно проигрываемых файлов. Второй параметр задает тип аудиопотока. В большинстве случаев здесь подойдет значение soundPool STREAM_MUSIC, хотя возможно использование и других аудиопотоков. Их назначение довольно очевидно. (STREAM_ALARM, STREAM_DTMF, STREAM_NOTIFICATION, STREAM_RING,STREAM_SYSTEM, STREAM_VOICE_CALL). Третий параметр задает sample-rate. В настоящее время он ни на что не влияет, поэтому здесь устанавливаем 0.
После того, как мы создали объект для SoundPool, с помощью setOnLoadCompleteListener добавим к нему OnLoadCompleteListener, который будет отслеживать завершение загрузки файлов. В качестве параметров метод onLoadComplete принимает объект SoundPool, номер загруженного сэмпла и статус завершения операции. В случае, если все прошло успешно, статус равен нулю.
Прежде чем проигрывать звуковые файлы их необходимо загрузить в SoundPool. Сделать это можно с помощью метода load. Метод имеет несколько реализаций, различающихся набором параметров и источником, поставляющим звуковые файлы. Можно загружать файлы из папки asset, можно из APK ресурсов, можно из файла, указав к нему путь, можно из FileDescriptor. Мы будем рассматривать ситуацию, когда звуковые сэмплы входят в состав APK пакета, то есть лежат в папке res/raw вашего проекта. Для загрузки нам понадобятся три параметра: ссылка на контекст из которого мы получаем доступ к ресурсам программы (в большинстве случаев подойдет this), ссылка на ресурс, полученная через объект R, и приоритет, который пока ни на что не влияет, и в документации рекомендуется устанавливать значение 1. Загруженные ресурсы можно выгрузить с помощью методов unload, если требуется удалить один сэмпл, и release — если нужно полностью очистить SoundPool.
Для проигрывания сэмпла используется метод play, имеющий следующие параметры:
- soundID переменная с номером сэмпла. Этот номер возвращается в результате выполнения метода load.
- leftVolume значение громкости левого канала (от 0.0 до 1.0)
- rightVolume значение громкости правого канала (от 0.0 до 1.0)
- priority приоритет потока (0 — самый низкий приоритет)
- loop сколько раз нужно повторить сэмпл (0 не повторять, -1 — зациклить)
- rate скорость воспроизведения (может изменяться от 0.5 до 2.0, 1 — нормальная скорость)
В результате выполнения метода play возвращается номер streamID (или 0 в случае ошибки), который можно использовать для управления воспроизведением. Например это значение используется при вызове методов pause и resume, stop, setVolume, setLoop. Если число максимально проигрываемых файлов превышено, то вызов очередного метода play приведет к завершению воспроизведения одного из проигрываемых в данный момент сэмплов.
Код нашего класса приведен ниже
package ru.mobilab.crazysong;
SoundPool и утечка памяти
На форумах встречаются сообщения о том, что использование SoundPool вызывает проблему утечки памяти. Какой-то внятной и проверенной информацию по этому поводу найти не удалось. Если вы не собираетесь больше проигрывать звуки, рекомендуется выполнить код
но похоже, что этот метод не решает проблему вAndroid 2.1. Если Вы располагаете информацией об этой проблеме и ее решении, просьба отписаться в комментариях.
Воспроизведение фоновой музыки в Android с помощью MediaPlayer
SoundPool отлично подходит для озвучивания различных игровых событий: выстрелов, взрывов, реплик. Однако для проигрывания фоновой музыки нужно использовать класс MediaPlayer. Метод create этого класса имеет два параметра: контекст и ссылку на ресурс или URI адрес музыкального файла. Для запуска/паузы/остановки воспроизведения служат методы start(), pause() и stop() соответственно. Все просто.
В случае, если Вы собираетесь подгружать файл из интернета, последовательность действий будет немного другая. Метод create использовать не нужно. Источник аудиоданных задается с помощью метода setDataSource, после которого нужно вызвать метод prepare(), блокирующий выполнение потока до тех пор, пока медиаплеер не будет готов к воспроизведению музыки. Метод prepareAsync() выполняет те же действия в асинхронном режиме, то есть не блокирует вызвавший его поток. В случае использования prepareAsync нужно использовать OnPreparedListener для определения момента, когда MediaPlayer готов к проигрыванию файла. Заметим, что при использовании метода create метод prepare вызывать не нужно, поскольку он вызывается внутри create.
Остался еще один актуальный вопрос: как определить, что воспроизведение файла закончилось? Для этой цели служит функция обратного вызова onCompletion. Чтобы привязать ее к нашему медиаплееру нужно выполнить следующий код:
Вот собственно и все. Воспроизведение звука не такая уж и сложная тема. Архив с проектом можетескачать здесь.
Источник
Building a simple audio app in Android (Part 2/3)
Building the app
Introduction
The goal of this series of articles is to get you started with the Android MediaPlayer API by going thru the journey of creating a very basic audio playback application called “A Simple MediaPlayer” app. This is the second part of a 3 part series that includes:
Part 2/3 — Building the app
This article will cover the following:
- How to use the MediaPlayer class (create, prepare, start, reset, seekTo) and get a working understanding of its state machine.
What does the app look like?
Where is the source code?
googlesamples/android-SimpleMediaPlayer
Contribute to android-SimpleMediaPlayer development by creating an account on GitHub.
The source code for the sample app is available on GitHub. This app allows you to play MP3 files from res/raw folder without streaming it from network audio sources. It exercises the MediaPlayer API so you can get a clear understanding of the states and the transitions by interacting with the app.
Building the app
The app uses the parts of the state machine described in Part 1/3 of the series. You can look at MediaPlayerHolder class of the sample app to see this in action.
- The MediaPlayerHolder implements an interface called PlayerAdapter which allows the MainActivity to control playback functions.
- The MainActivity creates a UI that allows the user to play, pause, and stop media playback. And it creates a MediaPlayerHolder object.
- The MainActivity implements an interface called PlaybackInfoListener which allows the MediaPlayerHolder to update it when media duration and progress changes.
Loading Media (prepare, prepareAsync)
To keep things simple, the audio files are loaded from the res/raw folder in this project. There is 1 file in this folder: jazz_in_paris.mp3 .
Playback controls (start, reset, stop, seekTo)
There are only 3 buttons in the UI of the sample app — PLAY, PAUSE, RESET. Here’s the code in MainActivity related to this. Note: The mPlayerAdapter implements PlayerAdapter , and it is how MediaPlayerHolder functionality is exposed to the MainActivity .
Here are a few methods in MediaPlayerHolder (which implements PlayerAdapter ) that actually manages the MediaPlayer .
MediaPlayer lifecycle
When you’re playing audio and you change your screen orientation, then there might be issues with playback. This article is just focused on MediaPlayer , and it doesn’t go into the client server architecture you would need to implement in order to handle audio playback in the background even when your app’s activities aren’t running or in the foreground.
When screen orientation changes, Android destroys the Activity and recreates it. In our sample code, we create the MediaPlayer and keep it around during the lifetime of the MainActivity . In order to keep things simple, we are going to override the default behavior of Activity to destroy itself and handle the screen configuration changes ourselves.
We do this by adding the following to the app’s AndroidManfiest.xml . You can learn more about this on developers.android.com.
It is important not to hold on to the MediaPlayer’s resources when no audio is being played back. The MediaPlayer holds lots of shared resources that are provided by the Android OS (such as codecs). And it’s really important to release these resources when not in use. The MediaPlayerHolder class has a release() method, which ends up releasing the MediaPlayer . This is called by the onStop() method of the MainActivity .
Once a MediaPlayer has been released, it can’t be used again. So a new one has to be created. The MediaPlayerHolder takes care of this, when the loadMedia(int) method is called, in order to load and prepare the MP3 file to be played from the APK.
The MainActivity does not support media playback when the app is moved to the background. In the onStop() method, playback is stopped, and the MediaPlayer is released.
In order to support playback in the background you should use a bound and started service, or use a MediaSession . We will cover each of these in other articles.
To continue building the app and integrating the SeekBar for continuous syncing of playback progress and scrubber, please checkout Part 3/3 of this series- Synchronizing with the SeekBar.
Источник
Building a simple audio app in Android (Part 1/3)
MediaPlayer introduction
Introduction
Android Media APIs encompass a lot of advanced functionality that allow developers to create rich media experiences. They include things like ExoPlayer , MediaSession , audio focus, volume shaping, and lots of other amazing capabilities just around media playback and control.
The goal of this series of articles is to get you started with the Android MediaPlayer API by going thru the journey of creating a very basic audio playback application called “A Simple MediaPlayer” app. This is the first part of a 3 part series that includes:
Part 1/3 — MediaPlayer introduction
This article will cover the following:
- How the MediaPlayer works by considering some simple audio playback tasks and how they map to the MediaPlayer state machine.
Basic MediaPlayer tasks
Here are the basic tasks that MediaPlayer needs to handle:
- Load a media file for playback. This is done with the methods setDataSource() , prepare() , and prepareAsync() .
- Start playback / Play audio. This is handled by start() .
- Pause playback (once playback has started). This is handled by pause() .
- Stop playback and reset the MediaPlayer, so that you can load another media file into it. This is handled by reset() .
- Find the length of a song (in ms). This is handled by getDuration() .
- Find what part of the song is playing. This is handled by getCurrentPosition() .
- Jump to a specific time position (in ms) in the song and play from there. This is handled by seekTo(position) .
- Check to see if audio is being played back right now. This is handled by isPlaying() .
- Find out when a song is done playing. This is handled by attaching a MediaPlayer.OnCompletionListener . Your code will get an onCompletion() callback from the listener.
- Deallocate resources used by the player. This is handled by release() , which releases all the resources attached to the player. After being released the player is no longer usable.
This list covers the basic playback tasks for audio content, but it isn’t exhaustive. There are more complex functions for sophisticated audio apps such as streaming media, dealing with audio focus, volume shaping, and working with MediaSession . For more information on these advanced topics, please consult the MediaPlayer API guide.
Simplified state machine
Here is a simplified description of MediaPlayer’s state machine for audio playback:
First create an instance of MediaPlayer .
- Then load the media file that you want into the player. This means using the setDataSource() method with a parameter that describes where the media file is coming from.
- Now you need to prepare your data source. There are two ways of doing this:
- Use prepare() . This method will block the calling thread so should only be used for data sources which are stored locally on the device.
- Use prepareAsync() . This method will prepare the data source asynchronously and should be used for remote or large data sources. Using this method you get a callback when your media is ready for playback, and you can enable media playback controls in your app’s UI at this point. You can use the MediaPlayer.OnPreparedListener to get notified when the player has loaded the content for you to start playback. You can attach this listener to your player using setOnPreparedListener(listener) .
Now that your audio has been loaded, you can play and pause your audio. And you can stop and restart playback.
- Play — use start() to tell the player to start playback. You can ask the player if it’s playing using isPlaying() .
- Pause — you can pause only if isPlaying() is true so always check this before you call pause() .
- Stop — use the reset() method to do this. It will stop playback and reset the player so that you can load other media files into it.
- Seek — use the seekTo() method with a time offset to move audio playback to the desired position. This is needed when you allow the user to move playback to any position in the currently loaded media.
When you are done with the instance of MediaPlayer, be sure to release() it. Once released, you have to create a new MediaPlayer object and start from Step 1 in order to play another media file.
To get started with building the app, please checkout Part 2/3 of this series- Building the app.
Источник