- Полный список
- MediaPlayer.OnCompletionListener ошибка
- A Step by Step Guide to Building an Android Audio Player App
- Part One – Setting up the Project.
- Step Two – Create the MediaPlayer Service
- Step Three – Constructing the MediaPlayer
- Step Four – Handling Audio Focus
- Step Five – Service Lifecycle Methods
- Step Six – Binding the Audio Player
- Step Seven – Activity Lifecycle Methods
- Extras – Loading Local Audio Files
- What is a BroadcastReceiver ?
- Lets Get Back to the Audio Player App
- Change of audio outputs (headphone removed)
- Handling Incoming Calls
- Redefine Methods
- Play New Audio Broadcast
- Register BroadcastReceiver S
- User Interactions
- Finishing Up
- Fast Forward
Полный список
MediaPlayer – класс, который позволит вам проигрывать аудио/видео файлы с возможностью сделать паузу и перемотать в нужную позицию. MediaPlayer умеет работать с различными источниками, это может быть: путь к файлу (на SD или в инете), адрес потока, Uri или файл из папки res/raw.
Напишем небольшое приложение аудио-плеер и используем в нем все эти возможности.
Project name: P1261_MediaPlayer
Build Target: Android 2.3.3
Application name: MediaPlayer
Package name: ru.startandroid.develop.p1261mediaplayer
Create Activity: MainActivity
Добавляем строки в strings.xml:
Так это выглядит на экране
Кнопки верхнего ряда запускают проигрывание треков из различных источников. Кнопки среднего ряда – это пауза, возобновление, стоп и чекбокс повторения трека. А в нижнем ряду кнопки перемотки назад/вперед и вывод в лог текущей информации.
Создайте папку res/raw и положите в нее какой-нить звуковой файл с именем explosion.mp3. Например, его можно скачать здесь — http://dl.dropboxusercontent.com/u/6197740/explosion.mp3.
Разбираемся. Сначала создаем константы-пути, которые будет использовать проигрыватель. Это файл в инете (DATA_HTTP), поток в инете (DATA_STREAM), файл на флэшке (DATA_SD) и Uri на мелодию из системы (DATA_URI). Для SD и Uri укажите ваши значения, чтобы такие файлы существовали. (По получению Uri в конце урока есть вспомогательный код)
В onCreate получаем AudioManager, находим на экране чекбокс и настраиваем так, чтобы он включал/выключал режим повтора для плеера.
onClickStart – метод для обработки нажатий на кнопки верхнего ряда. Сначала мы освобождаем ресурсы текущего проигрывателя. Затем в зависимости от нажатой кнопки стартуем проигрывание. Какие методы для этого используются?
setDataSource – задает источник данных для проигрывания
setAudioStreamType – задает аудио-поток, который будет использован для проигрывания. Их существует несколько: STREAM_MUSIC, STREAM_NOTIFICATION и п. Подробнее их можно посмотреть в доках по AudioManager. Предполагаю, что созданы они для того, чтобы можно было задавать разные уровни громкости, например, играм, звонкам и уведомлениям. Этот метод можно и пропустить, если вам не надо явно указывать какой-то поток. Насколько я понял, по умолчанию используется STREAM_MUSIC.
Далее используется метод prepare или prepareAsync (в паре с OnPreparedListener). Эти методы подготавливают плеер к проигрыванию. И, как понятно из названия, prepareAsync делает это асинхронно, и, когда все сделает, сообщит об этом слушателю из метода setOnPreparedListener. А метод prepare работает синхронно. Соотвественно, если хотим прослушать файл из инета, то используем prepareAsync, иначе наше приложение повесится, т.к. заблокируется основной поток, который обслуживает UI.
Ну и метод start запускает проигрывание.
В случае с raw-файлом мы используем метод create. В нем уже будет выполнен метод prepare и нам остается только выполнить start.
Далее мы для плеера включаем/выключаем повтор (setLooping) в зависимости от текущего значения чекбокса. И вешаем слушателя (setOnCompletionListener), который получит уведомление, когда проигрывание закончится.
В методе releaseMP мы выполняем метод release. Он освобождает используемые проигрывателем ресурсы, его рекомендуется вызывать когда вы закончили работу с плеером. Более того, хелп рекомендует вызывать этот метод и при onPause/onStop, если нет острой необходимости держать объект.
В методе onClick мы обрабатываем нажатия на кнопки управления проигрывателем. Какие здесь используются методы?
start – возобновляет проигрывание
seekTo – переход к определенной позиции трека (в милисекундах)
getCurrentPosition – получить текущую позицию (в милисекундах)
getDuration – общая продолжительность трека
isLooping – включен ли режим повтора
getStreamVolume – получить уровень громкости указанного потока
Далее идут методы
onPrepared – метод слушателя OnPreparedListener. Вызывается, когда плеер готов к проигрыванию.
onCompletion – метод слушателя OnCompletionListener. Вызывается, когда достигнут конец проигрываемого содержимого.
В методе onDestroy обязательно освобождаем ресурсы проигрывателя.
В манифесте добавляем права на интернет — android.permission.INTERNET.
Все сохраняем, запускаем приложение. Дизайн получившегося плеера, конечно, не ахти какой :), но нас сейчас интересует функционал.
Еще раз перечислю возможные действия. Нажимая верхние кнопки, мы запускаем проигрывание из различных источников. Кнопки среднего ряда позволят нам поставить паузу, возобновить/остановить проигрывание и включить режим повтора. Кнопки нижнего ряда перематывают назад/вперед на 3 сек (3000 мсек) и выводят инфу в лог.
Я включу проигрывание файла с SD и выведу инфу в лог (кнопка Info).
start SD
Playing true
Time 4702 / 170588
Looping false
Volume 10
Проигрывание идет, текущая позиция – 4-я секунда из 170, режим повтора выключен, громкость — 10.
Уменьшу громкость (кнопками устройства или эмулятора), включу режим повтора (чекбокс Loop), поставлю паузу (кнопка Pause) и снова выведу инфу в лог:
Playing false
Time 46237 / 170588
Looping true
Volume 6
Видим, что проигрывание остановилось, текущая позиция уже 46 секунд, режим повтора включен, а громкость уменьшилась до 6.
Теперь включу проигрывание потока (кнопка Stream). Смотрим лог:
08:49:13.799: D/myLogs(18805): start Stream
08:49:13.809: D/myLogs(18805): prepareAsync
08:49:27.589: D/myLogs(18805): onPrepared
Обратите внимание, сколько прошло времени с начала (prepareAsync) до завершения (onPrepared) подготовки проигрывателя – 14 секунд. Если бы мы использовали метод prepare, а не prepareAsync, то наше приложение было бы недоступно все это время.
Расскажу еще про несколько методов, которые я не использовал в примере, но о которых стоит знать.
Метод reset – сбрасывает плеер в начальное состояние, после него необходимо снова вызвать setDataSource и prepare. Похож на onRelease, но позволяет продолжить работу с этим же объектом. А вот после onRelease надо создавать новый объект MediaPlayer.
Метод setOnBufferingUpdateListener устанавливает слушателя буферизации проигрываемого потока. По идее слушатель будет получать процент буферизации, но у меня оно как-то странно работает — показывает или 0 или 100.
Метод setOnErrorListener устанавливает слушателя для получения ошибок. Особенно это полезно при методe prepareAsync. Если в ходе этого метода возникнут ошибки, то их можно поймать только так.
Метод setWakeMode позволяет ставить стандартную (PowerManager.WakeLock) блокировку на время проигрывания, указав тип блокировки. Не забудьте в манифесте добавить права на WAKE_LOCK.
По поводу видео. Метод setDisplay позволяет указать плееру, куда выводить изображение. Размещаете на экране компонент SurfaceView (вкладка Advanced), вызываете его метод getHolder и полученный объект передаете в setDisplay. Плеер выведет изображение на этот компонент.
Чтобы узнать размер проигрываемого изображения можно использовать методы getVideoHeight и getVideoWidth.
В хелпе класса MediaPlayer есть хорошая схема состояний плеера. Она кажется запутанной, но если посидеть и поразбираться, то вполне можно все понять. Схема полезная, советую вникнуть.
А здесь можно посмотреть какие форматы поддерживаются системой.
Также хелп любезно предоставляет нам код, который позволит просмотреть существующие медиа-файлы в системе:
На следующем уроке:
— работаем с SoundPool
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
MediaPlayer.OnCompletionListener ошибка
Из-за OnCompletionListener подчеркивается вся строка с ошибкой «Class «MainActivity» must either be declared abstract or implement abstract method «OnCompletion(MediaPlayer)» or «OnCompletionListener»«
В гугле ничего к сожалению не удалось найти.
Ошибка MediaPlayer’a
Здравствуйте форумчане.Создал кнопочку для проигрывания мелодии, но при проигрывании в консоли.
MediaPlayer ошибка веремени выполнения
По клику на ImageView должна воспроизвестись короткая мелодия, но вместо этого приложение падает.
«constructor MediaPlayer in class MediaPlayer cannot be applied to given types»
Проблема в строке «37—final MediaPlayer mp = new MediaPlayer(this,R.raw.sample);» Ошыбка .
Простой MediaPlayer
Нужно сделать простую програмку. В главном активити — Баттн, при нажатии на него появляется.
Static MediaPlayer
Добрый день! Пытался реализовать следующий алгоритм работы своего приложения: Пользователь.
MediaPlayer автореверс
Всем привет,вопрос такое ,можно как нибудь сделать,чтоб в медиаплеере воспроизводить песню ,не.
SoundPool vs MediaPlayer
Какой класс лучше использовать для проигрывания музыки? Под музыкой подразумеваю не короткий.
Регистрация MediaPlayer
Подскажите как зарегистрировать MediaPlayer, чтоб при открытии файла он появлялся в диалоге.
Источник
A Step by Step Guide to Building an Android Audio Player App
This tutorial is a step by step guide to building an Android Audio app, using the best and most efficient methodologies and APIs. This is a long tutorials, so I have split it into two discrete parts if it’s too much to digest in one read:
- Building a media player in a service, important for playing media in the background.
- Interacting with the service through BroadcastReceiver s ( PLAY, PAUSE, NEXT, PREVIOUS). How to handle edge use-cases like incoming calls, change of audio outputs (e.g. removing headphones).
Part One – Setting up the Project.
Create a new Project in Android Studio and add the following permissions in the AndroidManifest.xml file.
The app needs these permissions to access media files over the internet when streaming media. Since the focus of this article is building a media player app, you need the MEDIA_CONTENT_CONTROL to control media playback. You use the READ_PHONE_STATE permission to access phone state to listen to events like incoming calls so you can stop the audio while a call is in progress.
Step Two – Create the MediaPlayer Service
The core of the Audio Player app is the media player service. The following class is an example of this service. The class has multiple MediaPlayer implementations to handle events that can happen while playing audio. The last implementation, from AudioManager.OnAudioFocusChangeListener is necessary to handle requests for AudioFocus from other apps that want to play media files.
The code above is a template of all the methods that will handle the MediaPlayer events. The only code that is complete is the binding of the Service . You need to bind this service because it interacts with the activity to get the audio files. You can lean more about bound services in the documentation.
Declare the Service in the AndroidManifest.xml file
Step Three – Constructing the MediaPlayer
The Android multimedia framework supports a variety of common media types. One key component of this framework is the MediaPlayer class, which with minimal setup you can use to play audio and video. You can find a basic example of the MediaPlayer implementation in the documentation, but you will need more than this example Service to play media. Next I will describe the necessary methods that need to be setup in the MediaPlayerService class.
Create the following global instances of MediaPlayer and the String path of the audio in the Service class.
Now initialize the mediaPlayer :
When working with media, you need to implement some functions to handle basic action for playing media. These basic functions are Play, Stop, Pause, and Resume.
First add another global variable to store the pause/resume position.
Add if statements to make sure there are no problems while playing media.
Now that you have created the initialization functions it’s time to implement the @Override methods constructed in the initial Service template. These methods are important to the MediaPlayer because all the key actions the player will perform will be called from these methods. Replace the original methods in the Service template with the following.
Note: There are more @Override methods implemented in the initial Service template. These are useful in specific MediaPlayer events, but since the focus of this tutorial is building a general purpose media player I wont implement them.
Step Four – Handling Audio Focus
For a good user experience with audio in Android, you need to be careful that your app plays nicely with the system and other apps that also play media.
To ensure this good user experience the MediaPlayerService will have to handle AudioFocus events and these are handled in the last override method, onAudioFocusChange() . This method is a switch statement with the focus events as its case: s. Keep in mind that this override method is called after a request for AudioFocus has been made from the system or another media app.
What happens in each case: ?
- AudioManager.AUDIOFOCUS_GAIN – The service gained audio focus, so it needs to start playing.
- AudioManager.AUDIOFOCUS_LOSS – The service lost audio focus, the user probably moved to playing media on another app, so release the media player.
- AudioManager.AUDIOFOCUS_LOSS_TRANSIENT – Fucos lost for a short time, pause the MediaPlayer .
- AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK – Lost focus for a short time, probably a notification arrived on the device, lower the playback volume.
In addition to the override methods, you need two other functions to request and release audio focus from the MediaPlayer . The following code block contains all the audio focus methods described above. I took the onAudioFocusChange() вЂs code from the Android Developer documentation and made some changes, but this code gets the job done for this example.
First add a new global variable to the Service class.
Replace the Service вЂs onAudioFocusChange() method with the following and add the functions it uses.
If you want to learn more about audio focus then SitePoint article has a great tutorial.
Step Five – Service Lifecycle Methods
In this section I will focus on the Service lifecycle. These methods are crucial to the MediaPlayer because the Service lifecycle is closely connected to the MediaPlayer s. These methods will handle the initialization and resource management for the MediaPlayer .
I have inline comments to make it easier to understand.
The onStartCommand() handles the initialization of the MediaPlayer and the focus request to make sure there are no other apps playing media. In the onStartCommand() code I added an extra try-catch block to make sure the getExtras() method doesn’t throw a NullPointerException .
Another important method you need to implement is onDestroy() . In this method the MediaPlayer resources must be released, as this service is about to be destroyed and there is no need for the app to control the media resources.
The onDestroy() method also releases audio focus, this is more of a personal choice. If you release the focus in this method the MediaPlayerService will have audio focus until destroyed, if there are no interruptions from other media apps for audio focus.
If you want a more dynamic focus control, you can request audio focus when new media starts playing and release it in the onCompletion() method, so the service will have focus control only while playing something.
Step Six – Binding the Audio Player
In this section I will cover the final steps to bind the MediaPlayerService class to the MainActivity and provide it with audio to play. You must bind the Service to the Activity so they can interact with each other.
Add the following global variables to the MainActivity class.
The first is an instance of the Service and the second Boolean value contains the status of the Service , bound or not to the activity.
To handle Service binding, add the following to the MainActivity class.
Now it’s time to play some audio. The following function creates a new instance of the MediaPlayerService and sends a media file to play, so add it to the MainActivity .
The playAudio() function is not complete. I will return to this later when sending media files to the Service with a BroadcastReceiver .
Call the playAudio() function from the Activity s onCreate() method and reference an audio file.
Step Seven – Activity Lifecycle Methods
In this section I will cover basic, but crucial implementations of the MainActivity s life-cycle methods. If you call the playAudio() function from the Activity s onCreate() method the Service will start playing, but the app can easily crash.
Add the following methods to MainActivity to fix it. All these methods do is save and restore the state of the serviceBound variable and unbind the Service when a user closes the app.
Extras – Loading Local Audio Files
A user will likely want to load audio from the actual device instead of streaming them online. You can load audio files from the device by using ContentResolver .
Create a new Java class used as an audio object. The following class contains the crucial information an audio file needs, but you can add more if necessary.
Add the permission to AndroidManifest.xml.
This is necessary to load local media files from the Android device.
In the MainActivity class create a global ArrayList of Audio objects.
To get data from the device add the following function to MainActivity . It retrieves the data from the device in ascending order.
After retrieving data from the device the playAudio() function can play it on the Service .
In MainActivity вЂs onCreate() method add the following code. Be sure to have at least one audio track the service can play or the app will crash.
If you’re ready for more, then keep reading, or this is also a good opportunity to take a quick break before continuing.
Next I will focus on user interaction with the MediaPlayerService and handling interruptions that occur while playing media like incoming calls, change of audio outputs and other functionality needed to build a complete Audio Player app.
The key component for interacting with background services is BroadcastReceiver .
What is a BroadcastReceiver ?
Android system components and apps make system wide calls through intents with the help of sendBroadcast() , sendStickyBroadcast() or sendOrderedBroadcast() methods to notify interested applications. Broadcast intents can be useful for providing a messaging and event system between application components or used by the Android system to notify interested applications about key system events. Registered BroadcastReceiver s intercept these events broadcast to the whole Android system. The BroadcastReceiver s purpose is to wait for certain events to happen and to react to these events, but a BroadcastReceiver does not react to all the incoming events, only specific events. When a BroadcastReceiver detects a matching intent it will call its onReceive() method to handle it.
You can register a BroadcastReceiver in two ways, statically in AndroidManifest.xml or dynamically by using the registerReceiver() method at runtime.
For this tutorial, the BroadcastReceiver s are dynamically created since it’s important that the MediaPlayerService listens for events only when the player is active. It’s not a good user experience if the app starts playing audio unexpectedly after an event was triggered. If you register a receiver, you must unregister it when it’s no longer needed.
Lets Get Back to the Audio Player App
For a more complete audio app I added a RecyclerView , and with the help of the loadAudio() function, loaded local audio files to the RecyclerView . I also made changes to the color scheme and layout. I wont go into detail describing the process of adding the RecyclerView to the app, but you can see the end result on GitHub.
If you want to learn more about RecyclerView , then read my article.
Another change is the playAudio() function and the Service s onStartCommand() method, but I will return to these changes later and focus on the BroadcastReceiver s events and user interaction with the Service .
Change of audio outputs (headphone removed)
In media apps it’s common that when a user removes their headphones from the jack the media stops playing.
In the MediaPlayerService class create a BroadcastReceiver that listens to ACTION_AUDIO_BECOMING_NOISY , which means that the audio is about to become вЂnoisy’ due to a change in audio outputs. Add the following functions in the service class.
The BroadcastReceiver instance will pause the MediaPlayer when the system makes an ACTION_AUDIO_BECOMING_NOISY call. To make the BroadcastReceiver available you must register it. The registerBecomingNoisyReceiver() function handles this and specifies the intent action BECOMING_NOISY which will trigger this BroadcastReceiver .
You have not yet implemented the buildNotification() , so don’t worry when it shows an error.
Handling Incoming Calls
The next functions avoid audio playing during calls, which would be a terrible user experience.
First create the following global variables in the MediaPlayerService class.
Add the following function.
The callStateListener() function is an implementation of the PhoneStateListener that listens to TelephonyManager s state changes. TelephonyManager provides access to information about the telephony services on the device and listens for changes to the device call state and reacts to these changes.
Redefine Methods
I mentioned that I changed the methods described earlier in this article. I also made changes to the way audio files are passed to the Service . The audio files are loaded from the device with the help of the loadAudio() function. When the user wants to play audio, call the playAudio(int audioIndex) function with an index of the wanted audio from the ArrayList of loaded audio files.
When calling the playAudio() function for the first time, the ArrayList is stored in SharedPreferences together with the audio index number and when the MediaPlayerService wants to play new audio it loads it from SharedPreferences . This is one way to load the Audio array to the Service , but there are others.
Open build.gradle (app) and add dependencies for the Gson library.
The following class handles Data storage.
Now it’s time to change the playAudio() function. First in the MainActivity class create a global static String .
This string sends broadcast intents to the MediaPlayerService that the user wants to play new audio and has updated the cached index of the audio they want to play. The BroadcastReceiver that handles this intent is not created yet, for now replace your old playAudio() function in the MainActivity with the following.
The audio is not passed to the Service through putExtra() , so the Service has to load the data from the SharedPreferences and this is why the onStartCommand() method needs to be rewritten. I will return to this method at the end of this tutorial to give the complete onStartCommand() implementation. For now, add the following global variables to the MediaPlayerService class.
Play New Audio Broadcast
When the MediaPlayerService is playing something and the user wants to play a new track, you must notify the service that it needs to move to new audio. You need a way for the Service to listen to these “play new Audio” calls and act on them. How? Another BroadcastReceiver . I mentioned these “play new Audio” calls in the Redefine methods section when calling the playAudio() function.
In the MediaPlayerService class add the following functions.
When intercepting a PLAY_NEW_AUDIO intent, this BroadcastReceiver loads the updated index and updates the activeAudio object to the new media and the MediaPlayer is reset to play the new audio. The buildNotification() function is not yet implemented so it shows an error.
Register BroadcastReceiver S
In the Service s onCreate() method add the registration calls for the BroadcastReceiver s.
You must unregister all the registered BroadcastReceiver s when they are not needed anymore. This happens in the Service s onDestroy() method. Replace your current onDestroy() method with the following. Again, don’t worry about the removeNotification() , it’s implemented later.
When the Service is destroyed it must stop listening to incoming calls and release the TelephonyManager resources. Another final thing the Service handles before it’s destroyed is clearing the data stored in the SharedPreferences .
User Interactions
Interacting with the MediaPlayerService is one of the key features of an audio player app, because users don’t need to play media, but also need to have control over the app. This is not as easy as it looks when working with background services because there is no user interface in background threads. Android Lollipop introduced new features, including Android MediaStyle notifications.
Notification.MediaStyle allows you to add media buttons without having to create custom notifications. In this example I will use the MediaStyle s support library, NotificationCompat.MediaStyle to support older Android versions.
To have full control over media playback in the MediaPlayerService you need to create an instance of MediaSession . MediaSession allows interaction with media controllers, volume keys, media buttons, and transport controls. An app creates an instance of MediaSession when it wants to publish media playback information or handle media keys.
To build a MediaStyle notification for this example, the MediaPlayerService will make use of MediaSession s transport controls to add notification controls and publish MetaData so the Android system know that it’s playing audio.
Before moving on, add the following variables in the MediaPlayerService class.
The String variables are used to notify which action is triggered from the MediaSession callback listener. The rest of the instances relate to the MediaSession and a notification ID to uniquely identify the MediaStyle notification.
The following functions handle the initialization of the MediaSession and setting the MetaData to an active session. An important part of the following initMediaSession() function is setting the MediaSession callbacks to handle events coming from the notification buttons.
Add the following functions in the MediaPlayerService class.
The updateMetaData() method has a Bitmap image that you need to create, so add an image to the drawable folder of the project. The Callback() override methods make use of the media player key functions described earlier. Next add the media player functions mentioned earlier to the Service .
Now the service needs a way to build the MediaStyle notification, but the service needs a way to keep track of its playback status. For this create a new enumeration.
In your project create the following class.
Now the service has a way to keep track of its playback status add the following function for building the notifications.
When called, this function will build the notification according to the PlaybackStatus .
The main purpose of the buildNotification() function is building the notification UI and setting up all the events that will trigger when a user clicks a notification button. You generate the actions through PendingIntent s from the playbackAction() function. Add it to the MediaPlayerService .
Now that the service generates actions when the user clicks on the notification buttons it needs a way to handle these actions. Add the following action to the service.
This function figures out which of the playback actions is triggered and executes one of the MediaSession callback methods through its transport controls. The callback methods, implemented in the initMediaSession() function handle all the MediaPlayer actions.
Finishing Up
All that is left is to define the services onStartCommand() method. This method will handle the initialization of the MediaSession , the MediaPlayer , loading the cached audio playlist and building the MediaStyle notification. In the service class replace the old onStartCommand() method with the following.
In the initMediaPlayer() function replace the setDataSource() call with the following line
That sums it up for playing audio in a background service in Android. Now run the app and play audio the right way. Here is an example how my sample app looks. I added a RecyclerView to the app and the layout might look different, but the notification view and controls are the same.
Fast Forward
And that’s it! I understand there was a lot to absorb and understand in this tutorial, so if you have any questions or comments, please let me know below.
Источник