亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

【Android Dev Guide - 04】 - Media - 學習使

系統 1837 0

內容文字太多,根據自己的理解做了一些簡略的陳述,如果能自己對照看看官方英文原文,效果會好很多,翻譯的不好,有很多不當的地方還望指正,謝謝!后面有時間將寫一篇文章詳細解釋如何實現一個完整的音樂播放器


【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包含了一系列的常見多媒體格式的編碼與解碼支持。因此你可以簡單的把音頻,視頻,和圖片插入到你的AP當中去。你可以對從應用的資源文件下,從文件系統中的獨立文件或者從網絡上的流媒體的方式的多媒體文件進行播放視頻與音頻,這些都只需要使用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.

如果你的設備支持的話,你也可以通過使用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.

注意:你可以用標準輸出設備進行音頻的回放,目前,輸出設備是手機擴音器與藍牙耳機,你不可以在接聽電話的時候播放聲音文件。

【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)
使用MediaPlayer類,我們可以播放來自本地的資源,設備內置的資源,外存中的資源(可以是流媒體的格式)

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):

下面是一個如何播放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.

放在這個目錄下的文件最好不是原始音頻文件,可以放置那些可以進行解碼,系統支持的文件格式。

And here is how you might play from a URI available locally in the system (that you obtained through a Content Resolver, for instance):

下面是一個播放本地文件的例子:


Playing from a remote URL via HTTP streaming looks like this:

播放一個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 pass IllegalArgumentException and IOException when using setDataSource() , because the file you are referencing might not exist.

注意:從流媒體上播放的文件,必須支持在線下載。在使用 setDataSource() 的時候要注意捕獲 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的時候要注意特殊情況,有些時候在prepare()的時候有可能會花費很長的時間,我們不應該從UI線程中去調用準備音樂,這樣有可能引起ANR現象,這樣的話會用戶體驗會很糟糕。

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() 的方法,這個方法會在后臺準備好播放的音樂,并立即返回,這個時候會觸發 onPrepared() 方法,我們需要通過 setOnPreparedListener() 來處理后面需要的操作。

【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.

另一方面你需要注意的是播放狀態。在你編寫代碼的時候你必須時刻注意MediaPlayer的播放狀態,因為當你的播放器處于某些特定的狀態時,一些操作將失去效果,否則會出現一些異常的情況。

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.

文檔中有一個完整的MediaPlayer的播放狀態圖,它詳細的闡述了MediaPlayer狀態切換之間的方法。例如…………,你需要牢記那個狀態圖。如下:

【Android Dev Guide - 04】 - Media - 學習使用MediaPlayer播放音樂


【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.

簡單的理解就是用完的東西當然需要釋放,不然還是什么什么不好的后果啦,釋放的方法如下:

As an example, consider the problems that could happen if you forgot to release the 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 .)
一個簡單的例子來說明釋放的重要性,如果你在停止播放的時候沒有釋放MediaPlayer,卻在Activity重新啟動的時候又創建了一個MediaPlayer,那么就會發生錯誤。當屏幕轉動的時候,系統會重新創建Activity,那么也會重新創建一個MediaPlayer,這樣明顯有問題的。

【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.

如果你想把音樂在后臺播放,那么就需要使用service來控制MediaPlayer的實例。

【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.

首先,像一個Activity一樣,Service所有的活動都是默認在一個線程里面完成的,實際上,如果你在同一個AP里面運行Activity與Service,他們默認是使用同一個線程的,因此,如果你要同時處理比較繁重的事情,或者說追求更好的運行效果的話,還是最好使用不同的線程或者使用系統框架里面的異步機制。

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的時候的我們應該使用 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:

在異步執行的時候,有可能發生一些錯誤,我們需要捕獲那些問題,如下:

【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.

當我們設計一個播放器進行后臺播放的時候需要考慮設備進行休眠的情況,因為系統會在一定時候關閉一些不需要的功能,那樣可以節省電池,然而,如果你的需要后臺播放,那么就需要使得設備在空閑時也處于wake狀態。

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:

為了保證在播放音樂的時候CPU持續運行,我們需要調用 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來播放流媒體資源,那么還需要保持WIFI的LOCK


When you pause or stop your media, or when you no longer need the network, you should release the lock:

當我我們停止播放的時候,需要把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經常用來執行后臺任務,例如獲取郵件,同步數據,下載內容,在那些情況下,我們很難認識到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 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 ).

當在前臺執行的時候,我們可以使用 PendingIntent 啟動MainActiviy,如下圖:

【Android Dev Guide - 04】 - Media - 學習使用MediaPlayer播放音樂

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
    
    
      );
    
  
我們可以通過上面的方法來停止前臺播放效果

【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.

我們需要一種機制來處理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() 的第一個參數是一個 AudioManager.OnAudioFocusChangeListener ,當 Audio Focus發生變化的時候會觸發
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參數告訴我們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 the MediaPlayer .
  • 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:

你可以完成后臺兼容通過使用Audio Focus方法或者通過一個現實了audio focus的類。

You can create an instance of AudioFocusHelper class only if you detect that the system is running API level 8 or above. For example:

你可以在檢測到系統API>8的時候創建一個 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 :

我們之前提過到使用完MediaPlayer之后需要釋放資源。我們需要顯示的去調用清除的方法而不是依賴系統自動回收機制,因為那樣有可能在系統還沒有回收的時候你又創建了一個新的實例。所以在我們使用service的時候,我們需要重寫 onDestroy() method 來保證釋放了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的機會,而不僅僅是關閉的時候。我們可以暫時釋放之后又在需要的時候創建,當然當僅僅暫停一會的時候,我們可以持續擁有而不是過度的釋放又去創建。

【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會在發生一些導致音頻變得混雜的時候自動停止后臺播放的,例如,當用戶在用耳機聽歌的時候若是發生突然失去連接的情況會產生音頻混雜。然而,這個行為不是自動發生的。如果你沒有實現這個功能,則不會產生你需要的效果。

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:

你可以通過處理 ACTION_AUDIO_BECOMING_NOISY 的Intent來確保你的AP停止播放音樂在那種情況下,那個Intent需要在manifest文件中注冊一個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:
另外一個在MediaPlayer AP里面可能有用的功能是獲取用戶手機上已經存在的音樂,你可一通過 ContentResolver 來查詢外部的媒體


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平臺包括一個JET引擎用來讓你在AP中為JET音頻添加交互式的后臺播放。

JET 指在嵌入式設備上的音樂播放器, JET engine是控制游戲聲音特效的引擎,其使用MIDI格式,并可以控制游戲的時間進度)

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:

下面是一個如何從存放在SDcard中的.jet文件中創建JET回放的例子:


【6】Performing Audio Capture

音頻獲取比播放要稍微復雜一點,但是也還是比較簡單的,如下

Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:

  1. Create a new instance of android.media.MediaRecorder .
  2. Set the audio source using MediaRecorder.setAudioSource() . You will probably want to use MediaRecorder.AudioSource.MIC .
  3. Set output file format using MediaRecorder.setOutputFormat() .
  4. Set output file name using MediaRecorder.setOutputFile() .
  5. Set the audio encoder using MediaRecorder.setAudioEncoder() .
  6. Call MediaRecorder.prepare() on the MediaRecorder instance.
  7. To start audio capture, call MediaRecorder.start() .
  8. To stop audio capture, call MediaRecorder.stop() .
  9. When you are done with the MediaRecorder instance, call MediaRecorder.release() on it. Calling MediaRecorder.release() is always recommended to free the resource immediately.
The example class below illustrates how to set up, start and stop audio capture, and to play the recorded audio file.


終于寫完了,唉,花了不少時間啊,希望對大家有幫助,分享快樂!謝謝!

【Android Dev Guide - 04】 - Media - 學習使用MediaPlayer播放音樂


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。?!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 精品的一区二区三区 | 日本亚洲精品久久 | 一区二区中文字幕在线观看 | 成人精品视频网站 | 亚欧毛片 | 日韩av成人 | 日韩欧美亚洲每日更新网 | 亚洲国产精品久久日 | 成人欧美一区二区三区黑人免费 | 女人a级毛片 | 精品日本一区二区 | jizz成熟丰满老女人 | 亚洲精品一区二区三区美女 | 成人在线免费观看视频 | 手机看片福利盒子久久 | 日韩国产欧美 | 中文字幕亚洲综合精品一区 | 日本不卡免费在线 | 国产一在线精品一区在线观看 | 亚洲综合在线播放 | 国产精品久久久久天天影视 | 中文字幕专区在线亚洲 | 亚洲精品国产啊女成拍色拍 | 国产精品亚洲二线在线播放 | 国产成人一区二区三区视频免费 | 成人a视频片在线观看免费 成人a视频在线观看 | 精品一区二区三区在线观看l | 欧美成人亚洲欧美成人 | 深夜福利免费在线观看 | 亚洲欧洲精品成人久久曰 | se成人国产精品 | 极品专区高清在线 | 天天做天天爱夜夜爽毛片毛片 | 国产一区曰韩二区欧美三区 | 日本一级毛片2021免费 | 久久中文字幕久久久久91 | a免费视频 | 国产在线观看午夜不卡 | 午夜影视在线 | 免费黄色小视频在线观看 | 爱做久久久久久久久久 |