内容文字太多,根据自己的理解做了一些简略的陈述,如果能自己对照看看官方英文原文,效果会好很多,翻译的不好,有很多不当的地方还望指正,谢谢!后面有时间将写一篇文章详细解释如何实现一个完整的音乐播放器
【0】The Android multimedia framework includes support for encoding and decoding a variety of common media types, so that you can easily integrate audio, video and images into your applications. You can play audio or video from media files stored in your application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection, all usingMediaPlayer
APIs.
Android多媒体framework包含了一系列的常见多媒体格式的编码与解码支持。因此你可以简单的把音频,视频,和图片插入到你的AP当中去。你可以对从应用的资源文件下,从文件系统中的独立文件或者从网络上的流媒体的方式的多媒体文件进行播放视频与音频,这些都只需要使用mediaPlayer的API即可。
You can also record audio and video using theMediaRecorder
APIs if supported by the device hardware. Note that the emulator doesn't have hardware to capture audio or video, but actual mobile devices are likely to provide these capabilities.
如果你的设备支持的话,你也可以通过使用mediaRecorder的API进行录制视频与音频。注意模拟器没有硬件设备支持获取音频与视频,实际的手机设备是可以的。
This document shows you how to write a media-playing application that interacts with the user and the system in order to obtain good performance and a pleasant user experience.
这份文档将想你展示如何使用mediaPlayer播放多媒体文件,并且如何获得一个良好的运行效果与愉悦的用户体验。
Note:You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.
注意:你可以用标准输出设备进行音频的回放,目前,输出设备是手机扩音器与蓝牙耳机,你不可以在接听电话的时候播放声音文件。
One of the most important components of the media framework is theMediaPlayer
class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:
For a list of media formats that Android supports, see theAndroid Supported Media Formatsdocument.
Here is an example of how to play audio that's available as a local raw resource (saved in your application'sres/raw/
directory):
下面是一个如何播放AP程序下的资源的例子:
放在这个目录下的文件最好不是原始音频文件,可以放置那些可以进行解码,系统支持的文件格式。
And here is how you might play from a URI available locally in the system (that you obtained through a Content Resolver, for instance):
下面是一个播放本地文件的例子:
播放一个HTTP协议上的流媒体文件:
Note:If you're passing a URL to stream an online media file, the file must be capable of progressive download.
Caution:You must either catch or passIllegalArgumentException
andIOException
when usingsetDataSource()
, because the file you are referencing might not exist.
注意:从流媒体上播放的文件,必须支持在线下载。在使用setDataSource()的时候要注意捕获IllegalArgumentException
andIOException
UsingMediaPlayer
can be straightforward in principle. However, it's important to keep in mind that a few more things are necessary to integrate it correctly with a typical Android application. For example, the call toprepare()
can take a long time to execute, because it might involve fetching and decoding media data. So, as is the case with any method that may take long to execute, you shouldnever call it from your application's UI thread. Doing that will cause the UI to hang until the method returns, which is a very bad user experience and can cause an ANR (Application Not Responding) error. Even if you expect your resource to load quickly, remember that anything that takes more than a tenth of a second to respond in the UI will cause a noticeable pause and will give the user the impression that your application is slow.
使用MediaPlayer的时候要注意特殊情况,有些时候在prepare()的时候有可能会花费很长的时间,我们不应该从UI线程中去调用准备音乐,这样有可能引起ANR现象,这样的话会用户体验会很糟糕。
To avoid hanging your UI thread, spawn another thread to prepare theMediaPlayer
and notify the main thread when done. However, while you could write the threading logic yourself, this pattern is so common when usingMediaPlayer
that the framework supplies a convenient way to accomplish this task by using theprepareAsync()
method. This method starts preparing the media in the background and returns immediately. When the media is done preparing, theonPrepared()
method of theMediaPlayer.OnPreparedListener
, configured throughsetOnPreparedListener()
is called.
prepareAsync()
的方法,这个方法会在后台准备好播放的音乐,并立即返回,这个时候会触发onPrepared()
方法,我们需要通过setOnPreparedListener()
来处理后面需要的操作。
Another aspect of aMediaPlayer
that you should keep in mind is that it's state-based. That is, theMediaPlayer
has an internal state that you must always be aware of when writing your code, because certain operations are only valid when then player is in specific states. If you perform an operation while in the wrong state, the system may throw an exception or cause other undesireable behaviors.
另一方面你需要注意的是播放状态。在你编写代码的时候你必须时刻注意MediaPlayer的播放状态,因为当你的播放器处于某些特定的状态时,一些操作将失去效果,否则会出现一些异常的情况。
The documentation in theMediaPlayer
class shows a complete state diagram, that clarifies which methods move theMediaPlayer
from one state to another. For example, when you create a newMediaPlayer
, it is in theIdlestate. At that point, you should initialize it by callingsetDataSource()
, bringing it to theInitializedstate. After that, you have to prepare it using either theprepare()
orprepareAsync()
method. When theMediaPlayer
is done preparing, it will then enter thePreparedstate, which means you can callstart()
to make it play the media. At that point, as the diagram illustrates, you can move between theStarted,PausedandPlaybackCompletedstates by calling such methods asstart()
,pause()
, andseekTo()
, amongst others. When you callstop()
, however, notice that you cannot callstart()
again until you prepare theMediaPlayer
again.
Always keepthe state diagramin mind when writing code that interacts with aMediaPlayer
object, because calling its methods from the wrong state is a common cause of bugs.
文档中有一个完整的MediaPlayer的播放状态图,它详细的阐述了MediaPlayer状态切换之间的方法。例如…………,你需要牢记那个状态图。如下:
AMediaPlayer
can consume valuable system resources. Therefore, you should always take extra precautions to make sure you are not hanging on to aMediaPlayer
instance longer than necessary. When you are done with it, you should always callrelease()
to make sure any system resources allocated to it are properly released. For example, if you are using aMediaPlayer
and your activity receives a call toonStop()
, you must release theMediaPlayer
, because it makes little sense to hold on to it while your activity is not interacting with the user (unless you are playing media in the background, which is discussed in the next section). When your activity is resumed or restarted, of course, you need to create a newMediaPlayer
and prepare it again before resuming playback.
MediaPlayer
when your activity is stopped, but create a new one when the activity starts again. As you may know, when the user changes the screen orientation (or changes the device configuration in another way), the system handles that by restarting the activity (by default), so you might quickly consume all of the system resources as the user rotates the device back and forth between portrait and landscape, because at each orientation change, you create a newMediaPlayer
that you never release. (For more information about runtime restarts, seeHandling Runtime Changes.)
Service
and control theMediaPlayer
instance from there. You should be careful about this setup, because the user and the system have expectations about how an application running a background service should interact with the rest of the system. If your application does not fulfil those expectations, the user may have a bad experience. This section describes the main issues that you should be aware of and offers suggestions about how to approach them.如果你想把音乐在后台播放,那么就需要使用service来控制MediaPlayer的实例。
Activity
, all work in aService
is done in a single thread by default—in fact, if you're running an activity and a service from the same application, they use the same thread (the "main thread") by default. Therefore, services need to process incoming intents quickly and never perform lengthy computations when responding to them. If any heavy work or blocking calls are expected, you must do those tasks asynchronously: either from another thread you implement yourself, or using the framework's many facilities for asynchronous processing.首先,像一个Activity一样,Service所有的活动都是默认在一个线程里面完成的,实际上,如果你在同一个AP里面运行Activity与Service,他们默认是使用同一个线程的,因此,如果你要同时处理比较繁重的事情,或者说追求更好的运行效果的话,还是最好使用不同的线程或者使用系统框架里面的异步机制。
For instance, when using aMediaPlayer
from your main thread, you should callprepareAsync()
rather thanprepare()
, and implement aMediaPlayer.OnPreparedListener
in order to be notified when the preparation is complete and you can start playing. For example:例如在主线程里面使用MediaPlayer的时候的我们应该使用prepareAsync()
rather thanprepare()。
MediaPlayer
, you can accomplish this by implementing aMediaPlayer.OnErrorListener
and setting it in yourMediaPlayer
instance:
在异步执行的时候,有可能发生一些错误,我们需要捕获那些问题,如下:
When designing applications that play media in the background, the device may go to sleep while your service is running. Because the Android system tries to conserve battery while the device is sleeping, the system tries to shut off any of the phone's features that are not necessary, including the CPU and the WiFi hardware. However, if your service is playing or streaming music, you want to prevent the system from interfering with your playback.
In order to ensure that your service continues to run under those conditions, you have to use "wake locks." A wake lock is a way to signal to the system that your application is using some feature that should stay available even if the phone is idle.
当我们设计一个播放器进行后台播放的时候需要考虑设备进行休眠的情况,因为系统会在一定时候关闭一些不需要的功能,那样可以节省电池,然而,如果你的需要后台播放,那么就需要使得设备在空闲时也处于wake状态。To ensure that the CPU continues running while yourMediaPlayer
is playing, call thesetWakeMode()
method when initializing yourMediaPlayer
. Once you do, theMediaPlayer
holds the specified lock while playing and releases the lock when paused or stopped:
为了保证在播放音乐的时候CPU持续运行,我们需要调用setWakeMode()
WifiLock
as well, which you must acquire and release manually. So, when you start preparing theMediaPlayer
with the remote URL, you should create and acquire the Wi-Fi lock. For example:然而,如果你使用WIFI来播放流媒体资源,那么还需要保持WIFI的LOCK
当我我们停止播放的时候,需要把WIFI的LOCK释放
wifiLock.release();
Services are often used for performing background tasks, such as fetching emails, synchronizing data, downloading content, amongst other possibilities. In these cases, the user is not actively aware of the service's execution, and probably wouldn't even notice if some of these services were interrupted and later restarted.
Service经常用来执行后台任务,例如获取邮件,同步数据,下载内容,在那些情况下,我们很难认识到service的执行状态,也不能发现可能中间被中断过后来重启。
But consider the case of a service that is playing music. Clearly this is a service that the user is actively aware of and the experience would be severely affected by any interruptions. Additionally, it's a service that the user will likely wish to interact with during its execution. In this case, the service should run as a "foreground service." A foreground service holds a higher level of importance within the system—the system will almost never kill the service, because it is of immediate importance to the user. When running in the foreground, the service also must provide a status bar notification to ensure that users are aware of the running service and allow them to open an activity that can interact with the service.
有些时候我们想把一个service在前台执行,这样的话是机会不会被系统给杀死的。当在前台执行的时候,services需要提供一个状态栏的通知来保证用户知道正在执行的service,并且允许用户通过通知栏来打开一个activtiy并且与Service进行交互。In order to turn your service into a foreground service, you must create aNotification
for the status bar and callstartForeground()
from theService
. For example:
While your service is running in the foreground, the notification you configured is visible in the notification area of the device. If the user selects the notification, the system invokes the
PendingIntent
you supplied. In the example above, it opens an activity (MainActivity
).
当在前台执行的时候,我们可以使用PendingIntent
启动MainActiviy,如下图:
You should only hold on to the "foreground service" status while your service is actually performing something the user is actively aware of. Once that is no longer true, you should release it by callingstopForeground()
:
stopForeground(true);我们可以通过上面的方法来停止前台播放效果
When your application needs to output audio such as music or a notification, you should always request audio focus. Once it has focus, it can use the sound output freely, but it should always listen for focus changes. If it is notified that it has lost the audio focus, it should immediately either kill the audio or lower it to a quiet level (known as "ducking"—there is a flag that indicates which one is appropriate) and only resume loud playback after it receives focus again.
我们需要一种机制来处理Audio Focus的情况,这样可以避免重音的情况。这是必须的,Do you understand?
To request audio focus, you must callrequestAudioFocus()
from theAudioManager
, as the example below demonstrates:
The first parameter to
requestAudioFocus()
is anAudioManager.OnAudioFocusChangeListener
, whoseonAudioFocusChange()
method is called whenever there is a change in audio focus. Therefore, you should also implement this interface on your service and activities. For example:requestAudioFocus()
的第一个参数是一个AudioManager.OnAudioFocusChangeListener,当
Audio Focus发生变化的时候会触发
onAudioFocusChange()
focusChange
parameter tells you how the audio focus has changed, and can be one of the following values (they are all constants defined inAudioManager
):FocusChange参数告诉我们Audio focus是如何改变的,下面的几个值:
AUDIOFOCUS_GAIN
: You have gained the audio focus. AUDIOFOCUS_LOSS
: You have lost the audio focus for a presumably long time. You must stop all audio playback. Because you should expect not to have Ffocus back for a long time, this would be a good place to clean up your resources as much as possible. For example, you should release theMediaPlayer
. AUDIOFOCUS_LOSS_TRANSIENT
: You have temporarily lost audio focus, but should receive it back shortly. You must stop all audio playback, but you can keep your resources because you will probably get focus back shortly. AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
: You have temporarily lost audio focus, but you are allowed to continue to play audio quietly (at a low volume) instead of killing audio completely. Keep in mind that the audio focus APIs are available only with API level 8 (Android 2.2) and above, so if you want to support previous versions of Android, you should adopt a backward compatibility strategy that allows you to use this feature if available, and fall back seamlessly if not.
需要记住Audio Focus仅仅在API8以上才提供的
You can achieve backward compatibility either by calling the audio focus methods by reflection or by implementing all the audio focus features in a separate class (say,AudioFocusHelper
). Here is an example of such a class:
AudioFocusHelper
class only if you detect that the system is running API level 8 or above. For example:你可以在检测到系统API>8的时候创建一个AudioFocusHelper
class
MediaPlayer
object can consume a significant amount of system resources, so you should keep it only for as long as you need and callrelease()
when you are done with it. It's important to call this cleanup method explicitly rather than rely on system garbage collection because it might take some time before the garbage collector reclaims theMediaPlayer
, as it's only sensitive to memory needs and not to shortage of other media-related resources. So, in the case when you're using a service, you should always override theonDestroy()
method to make sure you are releasing theMediaPlayer
:我们之前提过到使用完MediaPlayer之后需要释放资源。我们需要显示的去调用清除的方法而不是依赖系统自动回收机制,因为那样有可能在系统还没有回收的时候你又创建了一个新的实例。所以在我们使用service的时候,我们需要重写onDestroy()
method 来保证释放了MediaPlayer,下面是例子:
MediaPlayer
as well, apart from releasing it when being shut down. For example, if you expect not to be able to play media for an extended period of time (after losing audio focus, for example), you should definitely release your existingMediaPlayer
and create it again later. On the other hand, if you only expect to stop playback for a very short time, you should probably hold on to yourMediaPlayer
to avoid the overhead of creating and preparing it again.我们需要尽可能的寻找可以释放MediaPlayer的机会,而不仅仅是关闭的时候。我们可以暂时释放之后又在需要的时候创建,当然当仅仅暂停一会的时候,我们可以持续拥有而不是过度的释放又去创建。
许多良好的AP会在发生一些导致音频变得混杂的时候自动停止后台播放的,例如,当用户在用耳机听歌的时候若是发生突然失去连接的情况会产生音频混杂。然而,这个行为不是自动发生的。如果你没有实现这个功能,则不会产生你需要的效果。
You can ensure your app stops playing music in these situations by handling theACTION_AUDIO_BECOMING_NOISY
intent, for which you can register a receiver by adding the following to your manifest:
你可以通过处理ACTION_AUDIO_BECOMING_NOISY的Intent来确保你的AP停止播放音乐在那种情况下,那个Intent需要在manifest文件中注册一个receiver。
ContentResolver
for external media:
ContentResolver
来查询外部的媒体
MediaPlayer
, you can do this:
JetPlayer
class.
Android平台包括一个JET引擎用来让你在AP中为JET音频添加交互式的后台播放。
(JET指在嵌入式设备上的音乐播放器,JET engine是控制游戏声音特效的引擎,其使用MIDI格式,并可以控制游戏的时间进度)
For a description of JET concepts and instructions on how to use the JetCreator authoring tool, see theJetCreator User Manual. The tool is available on Windows, OS X, and Linux platforms (Linux does not support auditioning of imported assets like with the Windows and OS X versions).
Here's an example of how to set up JET playback from a.jet
file stored on the SD card:
下面是一个如何从存放在SDcard中的.jet文件中创建JET回放的例子:
音频获取比播放要稍微复杂一点,但是也还是比较简单的,如下
Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:
android.media.MediaRecorder
. MediaRecorder.setAudioSource()
. You will probably want to useMediaRecorder.AudioSource.MIC
. MediaRecorder.setOutputFormat()
. MediaRecorder.setOutputFile()
. MediaRecorder.setAudioEncoder()
. MediaRecorder.prepare()
on the MediaRecorder instance. MediaRecorder.start()
. MediaRecorder.stop()
. MediaRecorder.release()
on it. CallingMediaRecorder.release()
is always recommended to free the resource immediately. 终于写完了,唉,花了不少时间啊,希望对大家有帮助,分享快乐!谢谢!