`
yunshangbuhe
  • 浏览: 228945 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
阅读更多
Tuesday, September 1, 2009 | 2:13 AM

Labels: Country: EMEA, Product: Android

Version 1.5 of the Android SDK introduced a bunch of cool new features for developers. Though not as glamorous as some APIs, the new audio manipulation classes - AudioTrack and AudioRecord - offer powerful functionality to developers looking to manipulate raw audio.

These classes let you record audio directly from the audio input hardware of the device, and stream PCM audio buffers to the audio hardware for playback. Strong sauce indeed for those of you looking to have more control over audio input and playback.

Enough talk - on to the code. To test out these new APIs I put together a simple Android app that listens to 10 seconds of input from the microphone and then plays it back through the speaker in reverse. Perfect for decoding secret messages in old Beatles albums. 

Start with the recording code. It's designed to record the incoming audio to a file on the SD Card that we'll read and playback later. As per the latest security patch, your application requires a uses-permission to record audio.

<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

The recording code here records a new set of 16bit mono audio at 11025Hz to reverseme.pcm on the SD card.

public void record() {
  int frequency = 11025;
  int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
  int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
  File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/reverseme.pcm");
  
  // Delete any previous recording.
  if (file.exists())
    file.delete();


  // Create the new file.
  try {
    file.createNewFile();
  } catch (IOException e) {
    throw new IllegalStateException("Failed to create " + file.toString());
  }
  
  try {
    // Create a DataOuputStream to write the audio data into the saved file.
    OutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os);
    DataOutputStream dos = new DataOutputStream(bos);
    
    // Create a new AudioRecord object to record the audio.
    int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration,  audioEncoding);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                              frequency, channelConfiguration,
                                              audioEncoding, bufferSize);
  
    short[] buffer = new short[bufferSize];  
    audioRecord.startRecording();


    while (isRecording) {
      int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
      for (int i = 0; i < bufferReadResult; i++)
        dos.writeShort(buffer[i]);
    }


    audioRecord.stop();
    dos.close();
  
  } catch (Throwable t) {
    Log.e("AudioRecord","Recording Failed");
  }
}

Next we create a playback method that reads the file and plays back the contents in reverse. It's important to set the audio data encoding (here PCM 16 bits), channel, and frequency values to the same settings used in the AudioRecord object. Then again, playing with the playback frequency might be have its own appeal.


public void play() {
  // Get the file we want to playback.
  File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/reverseme.pcm");
  // Get the length of the audio stored in the file (16 bit so 2 bytes per short)
  // and create a short array to store the recorded audio.
  int musicLength = (int)(file.length()/2);
  short[] music = new short[musicLength];


  try {
    // Create a DataInputStream to read the audio data back from the saved file.
    InputStream is = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(is);
    DataInputStream dis = new DataInputStream(bis);
     
    // Read the file into the music array.
    int i = 0;
    while (dis.available() > 0) {
      music[musicLength-1-i] = dis.readShort();
      i++;
    }


    // Close the input streams.
    dis.close();    


    // Create a new AudioTrack object using the same parameters as the AudioRecord
    // object used to create the file.
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                                           11025,
                                           AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                           AudioFormat.ENCODING_PCM_16BIT,
                                           musicLength,
                                           AudioTrack.MODE_STREAM);
    // Start playback
    audioTrack.play();
 
    // Write the music buffer to the AudioTrack object
    audioTrack.write(music, 0, musicLength);


  } catch (Throwable t) {
    Log.e("AudioTrack","Playback Failed");
  }
}

Finally, to drive this you need to update your application Activity to call the record and playback methods as appropriate. To keep this example as simple as possible I'm going to record for 10 seconds as soon as the application starts, and playback in reverse as soon as I've finished taking the sample.

To be more useful you'd almost certainly want to perform the playback operation in a Service and on a background thread.

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
   
  Thread thread = new Thread(new Runnable() {
    public void run() {
      record();
    }    
  });
  thread.start();


  try {
    wait(10000);
  } catch (InterruptedException e) {}
   
  isRecording = false;
   
  try {
    thread.join();
  } catch (InterruptedException e) {}
   
  play();
  finish();
}

The AudioTrack and AudioRecord classes offer a lot more functionality than I've demonstrated here. Using the AudioTrack streaming mode you can do processing of incoming audio and playback in near real time, letting you manipulate incoming or outgoing audio and perform signal processing on raw audio on the device.

Tell us how you've used these APIs in your Android apps in the comments!

Posted by: Reto Meier, EMEA Android Developer Advocate, Google UK
分享到:
评论

相关推荐

    Android录音 获取录音文件 录音时间

    在Android平台上进行录音操作是移动应用开发中常见的功能,它涉及到多媒体处理、文件操作以及用户交互等多个方面。本文将深入探讨如何在Android中实现录音、获取录音文件以及控制录音时间,同时也会提及与动画和文件...

    Android按下录音录音动画效果 ,自定义录音、播放动画View

    本文将深入探讨如何实现“Android按下录音录音动画效果,自定义录音、播放动画View”的技术要点,以及如何利用圆环形状来增强视觉效果。 首先,我们要创建一个自定义的`SoundRecordView`视图。这个视图将承载录音和...

    vue微信录音(本地录音)

    在Vue.js前端开发中,实现微信录音功能通常涉及到与微信API的交互,这需要对JavaScript、ECMAScript以及微信JS-SDK有深入的理解。微信录音功能主要应用于微信小程序或者通过微信浏览器访问的网页应用,它允许用户在...

    杭普HP系统录音盒和录音卡软件:

    "杭普HP系统录音盒和录音卡软件"这个标题指的是杭州普天(杭普)公司生产的,基于HP(惠普)系统的录音设备解决方案,包括硬件部分的录音盒和软件部分的录音卡驱动及管理软件。这类产品主要用于电话监控、客服中心、...

    杭普录音盒 HP2021录音系统软件驱动

    "杭普录音盒 HP2021录音系统软件驱动"这个标题指出,我们关注的是一个特定的录音设备,即杭普录音盒的2021年款,以及与之配套的录音系统软件和驱动程序。驱动程序在计算机硬件与操作系统之间起着桥梁的作用,确保...

    基于Android平台下的通话录音软件,帮助用户轻松实现通话录音和留言录音

    【基于Android平台下的通话录音软件】 在Android平台上开发通话录音软件是一项常见的移动应用开发任务,这类软件能够帮助用户记录他们的电话对话和语音留言,确保重要信息的留存和回顾。为了实现这一功能,开发者...

    杭普HP系列录音卡录音盒驱动与应用软件

    在IT领域,录音卡和录音盒是专业音频处理设备,常用于广播、音乐制作、电话监控等场景。杭普(Hang Pu)是一家提供此类设备的公司,其HP系列录音卡和录音盒以其良好的性能和稳定性受到一部分用户的青睐。然而,由于...

    kaios录音_录音_kaiOS录音_kaios_

    【kaiOS录音技术详解】 在移动操作系统领域,kaiOS是一个相对新兴但迅速崛起的平台,尤其在功能手机市场中占据了一席之地。kaiOS录音功能是该系统为用户提供的一个实用工具,允许用户记录音频,适用于会议纪要、...

    android通过调用系统录音或者选择现有录音实现录音上传

    在Android平台上,开发一款能够调用系统录音功能或选择已有录音文件进行上传的应用是一项常见的任务。这个项目专注于创建一个Android客户端,它不仅允许用户实时录制声音,还支持选择已有的音频文件,然后将这些音频...

    久酷尔录音软件

    【久酷尔录音软件】是一款专为用户设计的高效、便捷录音工具,其核心特性在于其小巧的体积、友好的用户界面以及易于操作的特点。这款软件不仅满足了基本的录音需求,而且在用户体验方面下了很大功夫,使得无论是初级...

    MATLAB录音并播放.zip_matlab_matlab 录音_matlab 语音_matlab录音

    在MATLAB中,录音和播放声音是一个常见的任务,尤其对于信号处理、音频分析或教学示例等应用。本文将深入探讨如何使用MATLAB实现这一功能,以及如何通过GUI界面进行交互式操作。 首先,MATLAB提供了`audiorecorder`...

    微信小程序 录音机 (源码)

    微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小程序 录音机 (源码)微信小...

    android录音功能实现

    在Android平台上,录音功能是应用程序开发中常见的需求之一,它为用户提供记录音频的能力。本文将深入探讨如何在Android中实现录音功能,以及如何播放录制的音频。我们将基于提供的"RecordDemo"项目进行讨论。 首先...

    录音器(专用歌曲录音)

    【录音器(专用歌曲录音)】是一款专为热爱唱歌和喊麦的用户设计的录音工具。它具有简单易用的界面和丰富的功能,使得录音体验更加便捷和专业。这款录音软件能够帮助用户录制高质量的声音,无论是深情的歌声还是激情...

    vb录音机源码

    【VB录音机源码解析】 VB(Visual Basic)是微软公司推出的一种面向对象的、可视化编程工具,它以其直观易用的界面和强大的功能深受程序员喜爱。本篇将深入探讨利用VB开发简单录音机源码的相关知识点。 1. **基础...

    Android开发--仿微信语音对讲录音,按住讲话进行录音,向上滑动可以进行取消录音.zip

    在Android开发中,实现“仿微信语音对讲录音”功能是一项常见的需求,它涉及到音频录制、用户交互以及事件处理等多个方面。在这个项目中,我们将会探讨如何构建这样一个系统,让用户可以按住按钮讲话进行录音,并...

    android 录音 及上传录音

    在Android平台上,录音和上传录音是常见的功能,广泛应用于各种应用程序,如社交、教育和娱乐。本文将深入探讨如何在Android应用中实现录音并上传录音文件,主要关注使用`MediaRecorder`类以及相关的网络上传技术。 ...

    Windows系统自带录音机

    Windows系统自带的录音机是许多用户用来捕捉声音的便捷工具,尤其对于那些需要录制音频笔记、教学内容或者简单的声音剪辑的用户来说非常实用。在Windows 10中,录音机可能并不像在Windows 7那样显眼,因为它可能被...

    MicSound.rar_delphi_录音 _录音 delphi_控制麦克风_音量控制

    在IT行业中,录音和音量控制是音频处理领域的重要组成部分,尤其在开发音频应用程序时,如音乐制作软件、语音识别工具或在线会议系统等。在Delphi编程环境中,开发者经常需要处理与录音和音量控制相关的任务。...

    android电话录音源代码

    11. **隐私问题**: 电话录音涉及用户隐私,确保遵守相关法律法规,明确告知用户并获取他们的同意。 以上就是基于“android电话录音源代码”的关键知识点。实际开发时,还需要结合具体的源代码进行深入理解和调整...

Global site tag (gtag.js) - Google Analytics