android 音频设备类型,Android 音频
Android 音頻Android Audio
02/28/2018
本文內容
Android OS 為多媒體提供了廣泛的支持,包括音頻和視頻。本指南重點介紹 Android 中的音頻,并介紹如何使用內置的音頻播放器和錄像機類以及低級音頻 API 播放和錄制音頻。還介紹了如何使用其他應用程序廣播的音頻事件,使開發人員能夠構建表現良好的應用程序。The Android OS provides extensive support for multimedia, encompassing both audio and video. This guide focuses on audio in Android and covers playing and recording audio using the built-in audio player and recorder classes, as well as the low-level audio API. It also covers working with Audio events broadcast by other applications, so that developers can build well-behaved applications.
概述Overview
現代移動設備采用了以前需要的設備 – 相機、音樂播放機和錄像機等專用功能。Modern mobile devices have adopted functionality that formerly would have required dedicated pieces of equipment – cameras, music players and video recorders. 因此,多媒體框架已成為移動 Api 中的一流功能。Because of this, multimedia frameworks have become a first-class feature in mobile APIs.
Android 為多媒體提供廣泛支持。Android provides extensive support for multimedia. 本文介紹如何在 Android 中使用音頻,并介紹了以下主題This article examines working with audio in Android, and covers the following topics
通過 MediaPlayer – 播放音頻使用內置 MediaPlayer 類播放音頻,包括本地音頻文件和具有類的流音頻文件 AudioTrack 。Playing Audio with MediaPlayer – Using the built-in MediaPlayer class to play audio, including local audio files and streamed audio files with the AudioTrack class.
錄制音頻 – 使用內置 MediaRecorder 類記錄音頻。Recording Audio – Using the built-in MediaRecorder class to record audio.
使用音頻通知 –使用音頻通知來創建正常運行的應用程序,這些應用程序可正確響應事件 (如通過掛起或取消其音頻輸出) 的傳入電話呼叫。Working with Audio Notifications – Using audio notifications to create well-behaved applications that respond correctly to events (such as incoming phone calls) by suspending or canceling their audio outputs.
使用低級別音頻 –AudioTrack通過直接寫入內存緩沖區來使用類播放音頻。Working with Low-Level Audio – Playing audio using the AudioTrack class by writing directly to memory buffers. 使用類記錄音頻 AudioRecord 并直接從內存緩沖區讀取。Recording audio using the AudioRecord class and reading directly from memory buffers.
要求Requirements
本指南需要 Android 2.0 (API 級別 5) 或更高版本。This guide requires Android 2.0 (API level 5) or higher. 請注意,必須在設備上進行調試音頻。Please note that debugging audio on Android must be done on a device.
需要 RECORD_AUDIO 在 AndroidManifest.XML中請求權限:It is necessary to request the RECORD_AUDIO permissions in AndroidManifest.XML:
用 MediaPlayer 類播放音頻Playing Audio with the MediaPlayer Class
在 Android 中播放音頻的最簡單方法是采用內置的 MediaPlayer 類。The simplest way to play audio in Android is with the built-in MediaPlayer class.
MediaPlayer 可以通過傳入文件路徑來播放本地文件或遠程文件。MediaPlayer can play either local or remote files by passing in the file path. 但是, MediaPlayer 非常區分狀態,并且在錯誤的狀態下調用其方法之一將導致引發異常。However, MediaPlayer is very state-sensitive and calling one of its methods in the wrong state will cause an exception to be thrown. 按照 MediaPlayer 下面所述的順序進行交互很重要,以免出現錯誤。It's important to interact with MediaPlayer in the order described below to avoid errors.
正在初始化和播放Initializing and Playing
播放音頻時 MediaPlayer 需要以下順序:Playing audio with MediaPlayer requires the following sequence:
Instantiate a new MediaPlayer object.
將文件配置為通過 SetDataSource 方法播放。Configure the file to play via the SetDataSource method.
調用 Prepare 方法來初始化播放器。Call the Prepare method to initialize the player.
調用 start 方法開始播放音頻。Call the Start method to start the audio playing.
下面的代碼示例演示了這種用法:The code sample below illustrates this usage:
protected MediaPlayer player;
public void StartPlayer(String filePath)
{
if (player == null) {
player = new MediaPlayer();
} else {
player.Reset();
player.SetDataSource(filePath);
player.Prepare();
player.Start();
}
}
掛起和繼續播放Suspending and Resuming Playback
可以通過調用 Pause 方法來掛起播放:The playback can be suspended by calling the Pause method:
player.Pause();
若要恢復暫停播放,請調用 Start 方法。To resume paused playback, call the Start method.
這將從播放中的暫停位置繼續:This will resume from the paused location in the playback:
player.Start();
在播放機上調用 Stop 方法會結束正在進行的播放:Calling the Stop method on the player ends an ongoing playback:
player.Stop();
當不再需要播放機時,必須通過調用 Release 方法釋放資源:When the player is no longer needed, the resources must be released by calling the Release method:
player.Release();
使用 MediaRecorder 類錄制音頻Using the MediaRecorder Class to Record Audio
MediaPlayer用于在 Android 中錄制音頻的必然結果是MediaRecorder類。The corollary to MediaPlayer for recording audio in Android is the MediaRecorder class. 與類似 MediaPlayer ,它是區分狀態的,并通過多個狀態進行轉換,使之能夠開始記錄。Like the MediaPlayer, it is state-sensitive and transitions through several states to get to the point where it can start recording. 若要錄制音頻, RECORD_AUDIO 必須設置權限。In order to record audio, the RECORD_AUDIO permission must be set. 有關如何設置應用程序權限的說明,請參閱使用 AndroidManifest.xml。For instructions on how to set application permissions see Working with AndroidManifest.xml.
初始化和記錄Initializing and Recording
錄制音頻時 MediaRecorder 需要執行以下步驟:Recording audio with the MediaRecorder requires the following steps:
Instantiate a new MediaRecorder object.
指定要使用哪些硬件設備通過 SetAudioSource 方法捕獲音頻輸入。Specify which hardware device to use to capture the audio input via the SetAudioSource method.
使用 SetOutputFormat 方法設置輸出文件音頻格式。Set the output file audio format using the SetOutputFormat method. 有關支持的音頻類型的列表,請參閱 Android 支持的媒體格式。For a list of supported audio types see Android Supported Media Formats.
Call the SetAudioEncoder method to set the audio encoding type.
調用 SetOutputFile 方法以指定寫入音頻數據的輸出文件的名稱。Call the SetOutputFile method to specify the name of the output file that the audio data is written to.
調用 Prepare 方法以初始化記錄器。Call the Prepare method to initialize the recorder.
調用 start 方法開始記錄。Call the Start method to start recording.
下面的代碼示例演示了此順序:The following code sample illustrates this sequence:
protected MediaRecorder recorder;
void RecordAudio (String filePath)
{
try {
if (File.Exists (filePath)) {
File.Delete (filePath);
}
if (recorder == null) {
recorder = new MediaRecorder (); // Initial state.
} else {
recorder.Reset ();
recorder.SetAudioSource (AudioSource.Mic);
recorder.SetOutputFormat (OutputFormat.ThreeGpp);
recorder.SetAudioEncoder (AudioEncoder.AmrNb);
// Initialized state.
recorder.SetOutputFile (filePath);
// DataSourceConfigured state.
recorder.Prepare (); // Prepared state
recorder.Start (); // Recording state.
}
} catch (Exception ex) {
Console.Out.WriteLine( ex.StackTrace);
}
}
正在停止錄制Stopping recording
若要停止錄制,請對 Stop MediaRecorder 執行以下操作:To stop the recording, call the Stop method on the MediaRecorder:
recorder.Stop();
清理Cleaning up
停止后 MediaRecorder ,調用 Reset 方法,使其重新進入其空閑狀態:Once the MediaRecorder has been stopped, call the Reset method to put it back into its idle state:
recorder.Reset();
當 MediaRecorder 不再需要時,必須通過調用 Release 方法釋放其資源:When the MediaRecorder is no longer needed, its resources must be released by calling the Release method:
recorder.Release();
管理音頻通知Managing Audio Notifications
AudioManager 類The AudioManager Class
AudioManager類提供對音頻通知的訪問,使應用程序能夠了解音頻事件發生的時間。The AudioManager class provides access to audio notifications that let applications know when audio events occur. 此服務還提供對其他音頻功能(如音量和鈴聲模式控制)的訪問。This service also provides access to other audio features, such as volume and ringer mode control. AudioManager允許應用程序處理音頻通知以控制音頻播放。The AudioManager allows an application to handle audio notifications to control audio playback.
管理音頻焦點Managing Audio Focus
設備的音頻資源 (內置播放機和錄像機) 由所有正在運行的應用程序共享。The audio resources of the device (the built-in player and recorder) are shared by all running applications.
從概念上講,這類似于臺式計算機上只有一個應用程序具有鍵盤焦點的應用程序:在通過鼠標單擊其中一個正在運行的應用程序選擇一個運行的應用程序后,鍵盤輸入只會轉到該應用程序。Conceptually, this is similar to applications on a desktop computer where only one application has the keyboard focus: after selecting one of the running applications by mouse-clicking it, the keyboard input goes only to that application.
音頻焦點與此類似,可防止多個應用程序同時播放或錄制音頻。Audio focus is a similar idea and prevents more than one application from playing or recording audio at the same time. 它比鍵盤焦點更復雜,因為它是自愿 – 的,應用程序可以忽略它當前沒有音頻焦點,而不考慮 – 和,因為有不同類型的音頻焦點可以請求。It is more complicated than keyboard focus because it is voluntary – the application can ignore that fact that it does not currently have audio focus and play regardless – and because there are different types of audio focus that can be requested. 例如,如果請求者只需播放音頻一小段時間,則可能會請求暫時性的焦點。For example, if the requestor is only expected to play audio for a very short time, it may request transient focus.
可能會立即授予音頻焦點,或最初拒絕音頻焦點,稍后將其授予。Audio focus may be granted immediately, or initially denied and granted later. 例如,如果某個應用程序在電話呼叫期間請求音頻焦點,則它將被拒絕,但在電話呼叫完成后,就可以獲得焦點。For example, if an application requests audio focus during a phone call, it will be denied, but focus may well be granted once the phone call is finished. 在這種情況下,將注冊偵聽器以便在音頻焦點消失時進行相應的響應。In this case, a listener is registered in order to respond accordingly if audio focus is taken away. 請求音頻焦點用于確定是否可以播放或錄制音頻。Requesting audio focus is used to determine whether or not it is OK to play or record audio.
有關音頻焦點的詳細信息,請參閱 管理音頻焦點。For more information about audio focus, see Managing Audio Focus.
為音頻焦點注冊回調Registering the Callback for Audio Focus
從注冊 FocusChangeListener 回調 IOnAudioChangeListener 是獲取和釋放音頻焦點的重要部分。Registering the FocusChangeListener callback from the IOnAudioChangeListener is an important part of obtaining and releasing audio focus. 這是因為,對音頻焦點的授予可能會推遲到稍后的時間。This is because the granting of audio focus may be deferred until a later time. 例如,應用程序可能會請求在有電話呼叫時播放音樂。For example, an application may request to play music while there is a phone call in progress. 電話呼叫結束之前,將不會授予音頻焦點。Audio focus will not be granted until the phone call is finished.
出于此原因,回調對象將作為參數傳遞到 GetAudioFocus 的方法 AudioManager 中,這是注冊回調的此調用。For this reason, the callback object is passed as a parameter into the GetAudioFocus method of the AudioManager, and it is this call that registers the callback. 如果最初拒絕音頻焦點,但后來卻被授予,則會通過調用回調來通知應用程序 OnAudioFocusChange 。If audio focus is initially denied but later granted, the application is informed by invoking OnAudioFocusChange on the callback. 使用相同的方法來告知應用程序音頻焦點已消失。The same method is used to tell the application that audio focus is being taken away.
當應用程序使用完音頻資源后,它將調用的 AbandonFocus 方法 AudioManager ,并再次傳入回調。When the application has finished using the audio resources, it calls the AbandonFocus method of the AudioManager, and again passes in the callback. 這會注銷回調并釋放音頻資源,以便其他應用程序可以獲得音頻焦點。This deregisters the callback and releases the audio resources, so that other applications may obtain audio focus.
請求音頻焦點Requesting Audio Focus
請求設備的音頻資源所需的步驟如下所示:The steps required to request the audio resources of the device are as follow:
獲取系統服務的句柄 AudioManager 。Obtain a handle to the AudioManager system service.
創建回調類的實例。Create an instance of the callback class.
通過對調用方法來請求設備的音頻資源 RequestAudioFocus AudioManager 。Request the audio resources of the device by calling the RequestAudioFocus method on the AudioManager . 參數是回調對象、流類型 (音樂、語音呼叫、振鈴等 ) 和請求的訪問權限的類型 (音頻資源可以暫時請求或無限期(例如) )。The parameters are the callback object, the stream type (music, voice call, ring etc.) and the type of the access right being requested (the audio resources can be requested momentarily or for an indefinite period, for example).
如果授予了該請求,則 playMusic 會立即調用方法,并且音頻開始播放。If the request is granted, the playMusic method is invoked immediately, and the audio starts to play back.
如果拒絕請求,則不執行其他操作。If the request is denied, no further action is taken. 在這種情況下,僅當稍后授予請求時,才會播放音頻。In this case, the audio will only play if the request is granted at a later time.
下面的代碼示例顯示了以下步驟:The code sample below shows these steps:
Boolean RequestAudioResources(INotificationReceiver parent)
{
AudioManager audioMan = (AudioManager) GetSystemService(Context.AudioService);
AudioManager.IOnAudioFocusChangeListener listener = new MyAudioListener(this);
var ret = audioMan.RequestAudioFocus (listener, Stream.Music, AudioFocus.Gain );
if (ret == AudioFocusRequest.Granted) {
playMusic();
return (true);
} else if (ret == AudioFocusRequest.Failed) {
return (false);
}
return (false);
}
正在釋放音頻焦點Releasing Audio Focus
播放跟蹤完成后,將 AbandonFocus 調用上的方法 AudioManager 。When the playback of the track is complete, the AbandonFocus method on AudioManager is invoked. 這允許其他應用程序獲取設備的音頻資源。This allows another application to gain the audio resources of the device. 如果其他應用程序已注冊自己的偵聽器,則這些應用程序將收到此音頻焦點更改的通知。Other applications will receive a notification of this audio focus change if they have registered their own listeners.
低級別音頻 APILow Level Audio API
低級別音頻 Api 可以更好地控制音頻播放和錄制,因為它們直接與內存緩沖區交互,而不是使用文件 Uri。The low-level audio APIs provide a greater control over audio playing and recording because they interact directly with memory buffers instead of using file URIs. 在某些情況下,這種方法更可取。There are some scenarios where this approach is preferable. 這些情況包括:Such scenarios include:
從加密的音頻文件播放時。When playing from encrypted audio files.
播放連續的短剪輯時。When playing a succession of short clips.
音頻流式處理。Audio streaming.
AudioTrack 類AudioTrack Class
AudioTrack類使用低級別音頻 api 進行記錄,并且是類的低級別等效項 MediaPlayer 。The AudioTrack class uses the low-level audio APIs for recording, and is the low-level equivalent of the MediaPlayer class.
正在初始化和播放Initializing and Playing
若要播放音頻, AudioTrack 必須實例化的新實例。To play audio, a new instance of AudioTrack must be instantiated. 傳入 構造函數 的參數列表指定如何播放緩沖區中包含的音頻示例。The argument list passed into the constructor specifies how to play the audio sample contained in the buffer. 參數包括:The arguments are:
流類型 – 語音、鈴聲、音樂、系統或警報。Stream type – Voice, ringtone, music, system or alarm.
–以 Hz 表示的采樣速率的頻率。Frequency – The sampling rate expressed in Hz.
通道配置 – Mono 或立體聲。Channel Configuration – Mono or stereo.
–8 位或16位編碼的音頻格式。Audio format – 8 bit or 16 bit encoding.
緩沖區大小 – (以字節為單位)。Buffer size – in bytes.
緩沖區模式 – 流式處理或靜態。Buffer mode – streaming or static.
構造后,將調用的 播放 方法 AudioTrack ,將其設置為開始播放。After construction, the Play method of AudioTrack is invoked, to set it up to start playing. 將音頻緩沖區寫入到 AudioTrack 開始播放:Writing the audio buffer to the AudioTrack starts the playback:
void PlayAudioTrack(byte[] audioBuffer)
{
AudioTrack audioTrack = new AudioTrack(
// Stream type
Stream.Music,
// Frequency
11025,
// Mono or stereo
ChannelOut.Mono,
// Audio encoding
Android.Media.Encoding.Pcm16bit,
// Length of the audio clip.
audioBuffer.Length,
// Mode. Stream or static.
AudioTrackMode.Stream);
audioTrack.Play();
audioTrack.Write(audioBuffer, 0, audioBuffer.Length);
}
暫停和停止播放Pausing and Stopping the Playback
調用 pause 方法以暫停播放:Call the Pause method to pause the playback:
audioTrack.Pause();
調用 Stop 方法將永久終止播放:Calling the Stop method will terminate the playback permanently:
audioTrack.Stop();
清理Cleanup
當 AudioTrack 不再需要時,必須通過調用 Release釋放其資源:When the AudioTrack is no longer needed, its resources must be released by calling Release:
audioTrack.Release();
AudioRecord 類The AudioRecord Class
AudioRecord類等效于 AudioTrack 錄制端。The AudioRecord class is the equivalent of AudioTrack on the recording side. 與類似 AudioTrack ,它會直接使用內存緩沖區來代替文件和 uri。Like AudioTrack, it uses memory buffers directly, in place of files and URIs. 它要求 RECORD_AUDIO 在清單中設置權限。It requires that the RECORD_AUDIO permission be set in the manifest.
初始化和記錄Initializing and Recording
第一步是構造一個新的 AudioRecord 對象。The first step is to construct a new AudioRecord object. 傳入 構造函數 的參數列表提供記錄所需的所有信息。The argument list passed into the constructor provides all the information required for recording. 與中不同 AudioTrack ,其中的參數是很大程度的枚舉,中的等效參數 AudioRecord 是整數。Unlike in AudioTrack, where the arguments are largely enumerations, the equivalent arguments in AudioRecord are integers. 其中包括:These include:
硬件音頻輸入源,如麥克風。Hardware audio input source such as microphone.
流類型 – 語音、鈴聲、音樂、系統或警報。Stream type – Voice, ringtone, music, system or alarm.
–以 Hz 表示的采樣速率的頻率。Frequency – The sampling rate expressed in Hz.
通道配置 – Mono 或立體聲。Channel Configuration – Mono or stereo.
–8 位或16位編碼的音頻格式。Audio format – 8 bit or 16 bit encoding.
緩沖區大小(以字節為單位)Buffer size-in bytes
構造后 AudioRecord ,將調用其 StartRecording 方法。Once the AudioRecord is constructed, its StartRecording method is invoked. 現在可以開始錄制了。It is now ready to begin recording. AudioRecord持續讀取音頻緩沖區的輸入,并將此輸入寫入音頻文件。The AudioRecord continuously reads the audio buffer for input, and writes this input out to an audio file.
void RecordAudio()
{
byte[] audioBuffer = new byte[100000];
var audRecorder = new AudioRecord(
// Hardware source of recording.
AudioSource.Mic,
// Frequency
11025,
// Mono or stereo
ChannelIn.Mono,
// Audio encoding
Android.Media.Encoding.Pcm16bit,
// Length of the audio clip.
audioBuffer.Length
);
audRecorder.StartRecording();
while (true) {
try
{
// Keep reading the buffer while there is audio input.
audRecorder.Read(audioBuffer, 0, audioBuffer.Length);
// Write out the audio file.
} catch (Exception ex) {
Console.Out.WriteLine(ex.Message);
break;
}
}
}
正在停止記錄Stopping the Recording
調用 Stop 方法會終止記錄:Calling the Stop method terminates the recording:
audRecorder.Stop();
清理Cleanup
當 AudioRecord 不再需要對象時,調用其 Release 方法會釋放與其關聯的所有資源:When the AudioRecord object is no longer needed, calling its Release method releases all resources associated with it:
audRecorder.Release();
總結Summary
Android OS 提供了一個功能強大的框架,用于播放、記錄和管理音頻。The Android OS provides a powerful framework for playing, recording and managing audio. 本文介紹如何使用高級和類播放和錄制音頻 MediaPlayer MediaRecorder 。This article covered how to play and record audio using the high-level MediaPlayer and MediaRecorder classes. 接下來,它探討了如何使用音頻通知在不同應用程序之間共享設備的音頻資源。Next, it explored how to use audio notifications to share the audio resources of the device between different applications. 最后,它介紹了如何使用低級別 Api 播放和錄制音頻,后者直接與內存緩沖區交互。Finally, it dealt with how to playback and record audio using the low-level APIs, which interface directly with memory buffers.
相關鏈接Related Links
總結
以上是生活随笔為你收集整理的android 音频设备类型,Android 音频的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机制图训练实训报告答案,制图实训报告
- 下一篇: uniapp实现音频播放抢占系统音频焦点