內(nèi)容文字太多,根據(jù)自己的理解做了一些簡(jiǎn)略的陳述,如果能自己對(duì)照看看官方英文原文,效果會(huì)好很多,翻譯的不好,有很多不當(dāng)?shù)牡胤竭€望指正,謝謝!后面有時(shí)間將寫一篇文章詳細(xì)解釋如何實(shí)現(xiàn)一個(gè)完整的音樂(lè)播放器
【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 using
MediaPlayer
APIs.
Android多媒體framework包含了一系列的常見多媒體格式的編碼與解碼支持。因此你可以簡(jiǎn)單的把音頻,視頻,和圖片插入到你的AP當(dāng)中去。你可以對(duì)從應(yīng)用的資源文件下,從文件系統(tǒng)中的獨(dú)立文件或者從網(wǎng)絡(luò)上的流媒體的方式的多媒體文件進(jìn)行播放視頻與音頻,這些都只需要使用mediaPlayer的API即可。
You can also record audio and video using the
MediaRecorder
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.
如果你的設(shè)備支持的話,你也可以通過(guò)使用mediaRecorder的API進(jìn)行錄制視頻與音頻。注意模擬器沒(méi)有硬件設(shè)備支持獲取音頻與視頻,實(shí)際的手機(jī)設(shè)備是可以的。
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播放多媒體文件,并且如何獲得一個(gè)良好的運(yùn)行效果與愉悅的用戶體驗(yàn)。
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.
注意:你可以用標(biāo)準(zhǔn)輸出設(shè)備進(jìn)行音頻的回放,目前,輸出設(shè)備是手機(jī)擴(kuò)音器與藍(lán)牙耳機(jī),你不可以在接聽電話的時(shí)候播放聲音文件。
【1】Using MediaPlayer
One of the most important components of the media framework is the
MediaPlayer
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:
- Local resources
- Internal URIs, such as one you might obtain from a Content Resolver
- External URLs (streaming)
For a list of media formats that Android supports, see the
Android Supported Media Formats
document.
Here is an example of how to play audio that's available as a local raw resource (saved in your application's
res/raw/
directory):
下面是一個(gè)如何播放AP程序下的資源的例子:
In this case, a "raw" resource is a file that the system does not try to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats.
放在這個(gè)目錄下的文件最好不是原始音頻文件,可以放置那些可以進(jìn)行解碼,系統(tǒng)支持的文件格式。
And here is how you might play from a URI available locally in the system (that you obtained through a Content Resolver, for instance):
下面是一個(gè)播放本地文件的例子:
Playing from a remote URL via HTTP streaming looks like this:
播放一個(gè)HTTP協(xié)議上的流媒體文件:
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 pass
IllegalArgumentException
and
IOException
when using
setDataSource()
, because the file you are referencing might not exist.
注意:從流媒體上播放的文件,必須支持在線下載。在使用
setDataSource()
的時(shí)候要注意捕獲
IllegalArgumentException
and
IOException
【1.1】Asynchronous Preparation
Using
MediaPlayer
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 to
prepare()
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 should
never 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的時(shí)候要注意特殊情況,有些時(shí)候在prepare()的時(shí)候有可能會(huì)花費(fèi)很長(zhǎng)的時(shí)間,我們不應(yīng)該從UI線程中去調(diào)用準(zhǔn)備音樂(lè),這樣有可能引起ANR現(xiàn)象,這樣的話會(huì)用戶體驗(yàn)會(huì)很糟糕。
To avoid hanging your UI thread, spawn another thread to prepare the
MediaPlayer
and notify the main thread when done. However, while you could write the threading logic yourself, this pattern is so common when using
MediaPlayer
that the framework supplies a convenient way to accomplish this task by using the
prepareAsync()
method. This method starts preparing the media in the background and returns immediately. When the media is done preparing, the
onPrepared()
method of the
MediaPlayer.OnPreparedListener
, configured through
setOnPreparedListener()
is called.
prepareAsync()
的方法,這個(gè)方法會(huì)在后臺(tái)準(zhǔn)備好播放的音樂(lè),并立即返回,這個(gè)時(shí)候會(huì)觸發(fā)
onPrepared()
方法,我們需要通過(guò)
setOnPreparedListener()
來(lái)處理后面需要的操作。
【1.2】Managing State
Another aspect of a
MediaPlayer
that you should keep in mind is that it's state-based. That is, the
MediaPlayer
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.
另一方面你需要注意的是播放狀態(tài)。在你編寫代碼的時(shí)候你必須時(shí)刻注意MediaPlayer的播放狀態(tài),因?yàn)楫?dāng)你的播放器處于某些特定的狀態(tài)時(shí),一些操作將失去效果,否則會(huì)出現(xiàn)一些異常的情況。
The documentation in the
MediaPlayer
class shows a complete state diagram, that clarifies which methods move the
MediaPlayer
from one state to another. For example, when you create a new
MediaPlayer
, it is in the
Idle
state. At that point, you should initialize it by calling
setDataSource()
, bringing it to the
Initialized
state. After that, you have to prepare it using either the
prepare()
or
prepareAsync()
method. When the
MediaPlayer
is done preparing, it will then enter the
Prepared
state, which means you can call
start()
to make it play the media. At that point, as the diagram illustrates, you can move between the
Started
,
Paused
and
PlaybackCompleted
states by calling such methods as
start()
,
pause()
, and
seekTo()
, amongst others. When you call
stop()
, however, notice that you cannot call
start()
again until you prepare the
MediaPlayer
again.
Always keep
the state diagram
in mind when writing code that interacts with a
MediaPlayer
object, because calling its methods from the wrong state is a common cause of bugs.
文檔中有一個(gè)完整的MediaPlayer的播放狀態(tài)圖,它詳細(xì)的闡述了MediaPlayer狀態(tài)切換之間的方法。例如…………,你需要牢記那個(gè)狀態(tài)圖。如下:
【1.3】Releasing the MediaPlayer
A
MediaPlayer
can consume valuable system resources. Therefore, you should always take extra precautions to make sure you are not hanging on to a
MediaPlayer
instance longer than necessary. When you are done with it, you should always call
release()
to make sure any system resources allocated to it are properly released. For example, if you are using a
MediaPlayer
and your activity receives a call to
onStop()
, you must release the
MediaPlayer
, 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 new
MediaPlayer
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 new
MediaPlayer
that you never release. (For more information about runtime restarts, see
Handling Runtime Changes
.)
【2】Using a Service with MediaPlayer
If you want your media to play in the background even when your application is not onscreen—that is, you want it to continue playing while the user is interacting with other applications—then you must start a
Service
and control the
MediaPlayer
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.
如果你想把音樂(lè)在后臺(tái)播放,那么就需要使用service來(lái)控制MediaPlayer的實(shí)例。
【2.1】Running asynchronously
First of all, like an
Activity
, all work in a
Service
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.
首先,像一個(gè)Activity一樣,Service所有的活動(dòng)都是默認(rèn)在一個(gè)線程里面完成的,實(shí)際上,如果你在同一個(gè)AP里面運(yùn)行Activity與Service,他們默認(rèn)是使用同一個(gè)線程的,因此,如果你要同時(shí)處理比較繁重的事情,或者說(shuō)追求更好的運(yùn)行效果的話,還是最好使用不同的線程或者使用系統(tǒng)框架里面的異步機(jī)制。
For instance, when using a
MediaPlayer
from your main thread, you should call
prepareAsync()
rather than
prepare()
, and implement a
MediaPlayer.OnPreparedListener
in order to be notified when the preparation is complete and you can start playing. For example:
例如在主線程里面使用MediaPlayer的時(shí)候的我們應(yīng)該使用
prepareAsync()
rather than
prepare()
。
【2.2】Handling asynchronous errors
On synchronous operations, errors would normally be signaled with an exception or an error code, but whenever you use asynchronous resources, you should make sure your application is notified of errors appropriately. In the case of a
MediaPlayer
, you can accomplish this by implementing a
MediaPlayer.OnErrorListener
and setting it in your
MediaPlayer
instance:
在異步執(zhí)行的時(shí)候,有可能發(fā)生一些錯(cuò)誤,我們需要捕獲那些問(wèn)題,如下:
【2.3】Using wake locks
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.
當(dāng)我們?cè)O(shè)計(jì)一個(gè)播放器進(jìn)行后臺(tái)播放的時(shí)候需要考慮設(shè)備進(jìn)行休眠的情況,因?yàn)橄到y(tǒng)會(huì)在一定時(shí)候關(guān)閉一些不需要的功能,那樣可以節(jié)省電池,然而,如果你的需要后臺(tái)播放,那么就需要使得設(shè)備在空閑時(shí)也處于wake狀態(tài)。
To ensure that the CPU continues running while your
MediaPlayer
is playing, call the
setWakeMode()
method when initializing your
MediaPlayer
. Once you do, the
MediaPlayer
holds the specified lock while playing and releases the lock when paused or stopped:
為了保證在播放音樂(lè)的時(shí)候CPU持續(xù)運(yùn)行,我們需要調(diào)用
setWakeMode()
However, the wake lock acquired in this example guarantees only that the CPU remains awake. If you are streaming media over the network and you are using Wi-Fi, you probably want to hold a
WifiLock
as well, which you must acquire and release manually. So, when you start preparing the
MediaPlayer
with the remote URL, you should create and acquire the Wi-Fi lock. For example:
然而,如果你使用WIFI來(lái)播放流媒體資源,那么還需要保持WIFI的LOCK
When you pause or stop your media, or when you no longer need the network, you should release the lock:
當(dāng)我我們停止播放的時(shí)候,需要把WIFI的LOCK釋放
wifiLock . release ();
【2.4】Running as a foreground service
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經(jīng)常用來(lái)執(zhí)行后臺(tái)任務(wù),例如獲取郵件,同步數(shù)據(jù),下載內(nèi)容,在那些情況下,我們很難認(rèn)識(shí)到service的執(zhí)行狀態(tài),也不能發(fā)現(xiàn)可能中間被中斷過(guò)后來(lái)重啟。
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.
有些時(shí)候我們想把一個(gè)service在前臺(tái)執(zhí)行,這樣的話是機(jī)會(huì)不會(huì)被系統(tǒng)給殺死的。當(dāng)在前臺(tái)執(zhí)行的時(shí)候,services需要提供一個(gè)狀態(tài)欄的通知來(lái)保證用戶知道正在執(zhí)行的service,并且允許用戶通過(guò)通知欄來(lái)打開一個(gè)activtiy并且與Service進(jìn)行交互。
In order to turn your service into a foreground service, you must create a
Notification
for the status bar and call
startForeground()
from the
Service
. 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
).
當(dāng)在前臺(tái)執(zhí)行的時(shí)候,我們可以使用
PendingIntent
啟動(dòng)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 calling
stopForeground()
:
stopForeground ( true );我們可以通過(guò)上面的方法來(lái)停止前臺(tái)播放效果
【2.5】Handling audio focus
Even though only one activity can run at any given time, Android is a multi-tasking environment. This poses a particular challenge to applications that use audio, because there is only one audio output and there may be several media services competing for its use. Before Android 2.2, there was no built-in mechanism to address this issue, which could in some cases lead to a bad user experience. For example, when a user is listening to music and another application needs to notify the user of something very important, the user might not hear the notification tone due to the loud music. Starting with Android 2.2, the platform offers a way for applications to negotiate their use of the device's audio output. This mechanism is called Audio Focus.
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.
我們需要一種機(jī)制來(lái)處理Audio Focus的情況,這樣可以避免重音的情況。這是必須的,Do you understand?
To request audio focus, you must call
requestAudioFocus()
from the
AudioManager
, as the example below demonstrates:
The first parameter to
requestAudioFocus()
is an
AudioManager.OnAudioFocusChangeListener
, whose
onAudioFocusChange()
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()
的第一個(gè)參數(shù)是一個(gè)
AudioManager.OnAudioFocusChangeListener
,當(dāng)
Audio Focus發(fā)生變化的時(shí)候會(huì)觸發(fā)
onAudioFocusChange()
The
focusChange
parameter tells you how the audio focus has changed, and can be one of the following values (they are all constants defined in
AudioManager
):
FocusChange參數(shù)告訴我們Audio focus是如何改變的,下面的幾個(gè)值:
-
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. - 下面是一個(gè)例子
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:
You can create an instance of
AudioFocusHelper
class only if you detect that the system is running API level 8 or above. For example:
你可以在檢測(cè)到系統(tǒng)API>8的時(shí)候創(chuàng)建一個(gè)
AudioFocusHelper
class
【2.6】Performing cleanup
As mentioned earlier, a
MediaPlayer
object can consume a significant amount of system resources, so you should keep it only for as long as you need and call
release()
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 the
MediaPlayer
, 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 the
onDestroy()
method to make sure you are releasing the
MediaPlayer
:
我們之前提過(guò)到使用完MediaPlayer之后需要釋放資源。我們需要顯示的去調(diào)用清除的方法而不是依賴系統(tǒng)自動(dòng)回收機(jī)制,因?yàn)槟菢佑锌赡茉谙到y(tǒng)還沒(méi)有回收的時(shí)候你又創(chuàng)建了一個(gè)新的實(shí)例。所以在我們使用service的時(shí)候,我們需要重寫
onDestroy()
method 來(lái)保證釋放了MediaPlayer,下面是例子:
You should always look for other opportunities to release your
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 existing
MediaPlayer
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 your
MediaPlayer
to avoid the overhead of creating and preparing it again.
我們需要盡可能的尋找可以釋放MediaPlayer的機(jī)會(huì),而不僅僅是關(guān)閉的時(shí)候。我們可以暫時(shí)釋放之后又在需要的時(shí)候創(chuàng)建,當(dāng)然當(dāng)僅僅暫停一會(huì)的時(shí)候,我們可以持續(xù)擁有而不是過(guò)度的釋放又去創(chuàng)建。
【3】Handling the AUDIO_BECOMING_NOISY Intent
Many well-written applications that play audio automatically stop playback when an event occurs that causes the audio to become noisy (ouput through external speakers). For instance, this might happen when a user is listening to music through headphones and accidentally disconnects the headphones from the device. However, this behavior does not happen automatically. If you don't implement this feature, audio plays out of the device's external speakers, which might not be what the user wants.
許多良好的AP會(huì)在發(fā)生一些導(dǎo)致音頻變得混雜的時(shí)候自動(dòng)停止后臺(tái)播放的,例如,當(dāng)用戶在用耳機(jī)聽歌的時(shí)候若是發(fā)生突然失去連接的情況會(huì)產(chǎn)生音頻混雜。然而,這個(gè)行為不是自動(dòng)發(fā)生的。如果你沒(méi)有實(shí)現(xiàn)這個(gè)功能,則不會(huì)產(chǎn)生你需要的效果。
You can ensure your app stops playing music in these situations by handling the
ACTION_AUDIO_BECOMING_NOISY
intent, for which you can register a receiver by adding the following to your manifest:
你可以通過(guò)處理
ACTION_AUDIO_BECOMING_NOISY
的Intent來(lái)確保你的AP停止播放音樂(lè)在那種情況下,那個(gè)Intent需要在manifest文件中注冊(cè)一個(gè)receiver。
【4】Retrieving Media from a Content Resolver
Another feature that may be useful in a media player application is the ability to retrieve music that the user has on the device. You can do that by querying the
ContentResolver
for external media:
另外一個(gè)在MediaPlayer AP里面可能有用的功能是獲取用戶手機(jī)上已經(jīng)存在的音樂(lè),你可一通過(guò)
ContentResolver
來(lái)查詢外部的媒體
To use this with the
MediaPlayer
, you can do this:
【5】Playing JET content
The Android platform includes a JET engine that lets you add interactive playback of JET audio content in your applications. You can create JET content for interactive playback using the JetCreator authoring application that ships with the SDK. To play and manage JET content from your application, use the
JetPlayer
class.
Android平臺(tái)包括一個(gè)JET引擎用來(lái)讓你在AP中為JET音頻添加交互式的后臺(tái)播放。
( JET 指在嵌入式設(shè)備上的音樂(lè)播放器, JET engine是控制游戲聲音特效的引擎,其使用MIDI格式,并可以控制游戲的時(shí)間進(jìn)度)
For a description of JET concepts and instructions on how to use the JetCreator authoring tool, see the
JetCreator 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:
下面是一個(gè)如何從存放在SDcard中的.jet文件中創(chuàng)建JET回放的例子:
【6】Performing Audio Capture
音頻獲取比播放要稍微復(fù)雜一點(diǎn),但是也還是比較簡(jiǎn)單的,如下
Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:
-
Create a new instance of
android.media.MediaRecorder
. -
Set the audio source using
MediaRecorder.setAudioSource()
. You will probably want to useMediaRecorder.AudioSource.MIC
. -
Set output file format using
MediaRecorder.setOutputFormat()
. -
Set output file name using
MediaRecorder.setOutputFile()
. -
Set the audio encoder using
MediaRecorder.setAudioEncoder()
. -
Call
MediaRecorder.prepare()
on the MediaRecorder instance. -
To start audio capture, call
MediaRecorder.start()
. -
To stop audio capture, call
MediaRecorder.stop()
. -
When you are done with the MediaRecorder instance, call
MediaRecorder.release()
on it. CallingMediaRecorder.release()
is always recommended to free the resource immediately.
終于寫完了,唉,花了不少時(shí)間啊,希望對(duì)大家有幫助,分享快樂(lè)!謝謝!
【Android Dev Guide - 04】 - Media - 學(xué)習(xí)使用MediaPlayer播放音樂(lè)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
