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:

96c67892caafd66636f1466cd07de2b9.png

用 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值