欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 录音与播放功能的简单实例

程序员文章站 2023-10-19 21:41:41
 android 录音与播放功能的简单实例 最近在研究android中一些常用的功能,像地图、拍照、录音和播放的实现等等,还有一些侧滑、动画等是如何实现的。...

 android 录音与播放功能的简单实例

最近在研究android中一些常用的功能,像地图、拍照、录音和播放的实现等等,还有一些侧滑、动画等是如何实现的。
今天就把录音和播放的实现分享一下,录音和播放比较简单,利用android内部的类即可实现。

1、先看下运行后的界面:

以下三张图分别是进入、录音、播放时的。

  Android 录音与播放功能的简单实例Android 录音与播放功能的简单实例Android 录音与播放功能的简单实例

2、layout布局文件

<?xml version="1.0" encoding="utf-8"?> 
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" > 
 
  <textview 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignparenttop="true" 
    android:background="@drawable/switcherbar_bg" 
    android:gravity="center" 
    android:text="@string/audio_record_title" 
    android:textcolor="#ffffff" 
    android:textsize="16sp" /> 
 
  <linearlayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_centerinparent="true" 
    android:orientation="vertical" 
    android:paddingleft="10dip" 
    android:paddingright="10dip" > 
 
    <textview 
      android:id="@+id/audio_record_time" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="00:00" /> 
 
    <linearlayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_margintop="10dip" 
      android:orientation="horizontal" > 
 
      <button 
        android:id="@+id/audio_record_start" 
        android:layout_width="0dip" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:background="@drawable/searchbtn_normal" 
        android:text="开始录音" 
        android:textsize="14sp" /> 
 
      <button 
        android:id="@+id/audio_record_stop" 
        android:layout_width="0dip" 
        android:layout_height="wrap_content" 
        android:layout_marginleft="5dip" 
        android:layout_weight="1" 
        android:background="@drawable/searchbtn_bg" 
        android:text="结束录音" 
        android:textsize="14sp" /> 
    </linearlayout> 
 
    <linearlayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_margintop="10dip" 
      android:orientation="horizontal" > 
 
      <button 
        android:id="@+id/audio_record_play" 
        android:layout_width="0dip" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:background="@drawable/searchbtn_normal" 
        android:text="播放录音" 
        android:textsize="14sp" /> 
 
      <button 
        android:id="@+id/audio_record_select" 
        android:layout_width="0dip" 
        android:layout_height="wrap_content" 
        android:layout_marginleft="5dip" 
        android:layout_weight="1" 
        android:background="@drawable/searchbtn_bg" 
        android:text="确定选择" 
        android:textsize="14sp" /> 
    </linearlayout> 
  </linearlayout> 
 
</relativelayout> 

3 activity类

录音涉及到二个activity,第一个activity比较简单,我这里大概说下,其实就是有个按钮,点击后转移第二个activity,录音返回后,在第一个activity中获取录音的文件名、时长等。

第一个activity部分代码:

 // 录音事件 
  ksly_btn.setonclicklistener(new onclicklistener() { 
    @override 
    public void onclick(view v) { 
      intent intent = new intent(maintainvisiteditactivity.this, audiorecordactivity.class); 
      intent.setaction(intent.action_view); 
      intent.putextra("duration", entity.getvoiceduration()); 
      intent.putextra("filename", entity.getvoicerecord()); 
      startactivityforresult(intent, voice_recode); 
    } 
  }); 
 
@override 
protected void onactivityresult(int requestcode, int resultcode, intent data) { 
  super.onactivityresult(requestcode, resultcode, data); 
 
  if (requestcode == voice_recode && resultcode == audiorecordactivity.success) { 
    entity.setvoiceduration(data.getlongextra("duration", 0));// 时长 
    entity.setvoicerecord(data.getstringextra("filename"));// 文件名(绝对路径) 
    ksly_time.settext(datetimeutils.formattomillisecond(entity.getvoiceduration())); 
  } 
} 

第二个activity代码:

这里要注意一下,就是需要捕获返回键,处理一下,就是点击返回键时,也返回个状态码,以表示没有录音成功。

package com.whowii.ct.cm.activity; 
 
import java.io.file; 
import java.io.ioexception; 
import java.text.simpledateformat; 
import java.util.date; 
import java.util.timer; 
import java.util.timertask; 
 
import android.app.activity; 
import android.content.intent; 
import android.media.mediaplayer; 
import android.media.mediaplayer.oncompletionlistener; 
import android.media.mediarecorder; 
import android.os.bundle; 
import android.os.handler; 
import android.os.message; 
import android.util.log; 
import android.view.keyevent; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.view.window; 
import android.widget.button; 
import android.widget.textview; 
import android.widget.toast; 
 
import com.whowii.ct.cm.r; 
import com.whowii.ct.cm.command.queryparams; 
import com.whowii.ct.cm.utils.datetimeutils; 
import com.whowii.ct.cm.utils.sdcardutils; 
 
/** 
 * 录制音频 
 * 
 * @author administrator 
 * 
 */ 
public class audiorecordactivity extends activity { 
  private textview audio_record_time; 
  private button audio_record_start, audio_record_stop, audio_record_play, audio_record_select; 
  private mediarecorder mediarecorder; 
  private final string tag = audiorecordactivity.class.getsimplename(); 
  private boolean isidle = true;// 当前是否空闲,false:表示正在录音 
  private long starttime = 0, stoptime = 0, duration = 0;// 开始时间、结束时间、录音时长 
  private string filename = null;// 存储录音文件的路径 
  private timer timer = null;// timer计时器 
  public static final int success = 1;// 录制成功; 
  public static final int failure = 0;// 录制失败 
  private mediaplayer mediaplayer; 
  private timertask task = new timertask() { 
    final handler handler = new handler() { 
      public void handlemessage(message message) { 
        bundle data = message.getdata(); 
        audio_record_time.settext(datetimeutils.formattomillisecond(data.getlong("time"))); 
      } 
    }; 
 
    public void run() { 
      message message = new message(); 
      long t = system.currenttimemillis(); 
      bundle data = new bundle(); 
      data.putlong("time", t - starttime); 
      message.setdata(data); 
      handler.sendmessage(message); 
    } 
  }; 
 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    requestwindowfeature(window.feature_no_title); // 设置无标题栏 
 
    setcontentview(r.layout.audio_record); 
    mediaplayer = new mediaplayer(); 
 
    initcontrol(); 
    setlistener(); 
 
    timer = new timer(true); 
    filename = getintent().getstringextra("filename"); 
    duration = getintent().getlongextra("duration", 0); 
  } 
 
  private void initcontrol() { 
    audio_record_time = (textview) findviewbyid(r.id.audio_record_time); 
    audio_record_start = (button) findviewbyid(r.id.audio_record_start); 
    audio_record_stop = (button) findviewbyid(r.id.audio_record_stop); 
    audio_record_play = (button) findviewbyid(r.id.audio_record_play); 
    audio_record_select = (button) findviewbyid(r.id.audio_record_select); 
  } 
 
  private void setlistener() { 
    // 播放完成事件 
    mediaplayer.setoncompletionlistener(new oncompletionlistener() { 
      @override 
      public void oncompletion(mediaplayer mp) { 
        isidle = true; 
        audio_record_play.settext("播放录音"); 
        audio_record_play.setbackgroundresource(r.drawable.searchinput_bg); 
      } 
    }); 
    // 开始录音 
    audio_record_start.setonclicklistener(new onclicklistener() { 
      @override 
      public void onclick(view v) { 
        if (!isidle) { 
          return; 
        } 
        if (!sdcardutils.sdcardexists()) { 
          toast.maketext(audiorecordactivity.this, "缺少sd卡,请先插入后再操作!", toast.length_long).show(); 
          return; 
        } 
        audio_record_start.settext("开始录音"); 
        audio_record_start.setenabled(true); 
 
        duration = 0; 
        starttime = system.currenttimemillis(); 
        filename = queryparams.cache_audio_path; 
        filename += new simpledateformat("yyyymmdd_hhmmss").format(new date(starttime)) + ".amr"; 
        file file = new file(filename); 
 
        mediarecorder = new mediarecorder(); 
        mediarecorder.setoutputfile(file.getabsolutepath()); 
        mediarecorder.setaudiosource(mediarecorder.audiosource.mic); 
        mediarecorder.setoutputformat(mediarecorder.outputformat.three_gpp); 
        mediarecorder.setaudioencoder(mediarecorder.audioencoder.amr_nb); 
        try { 
          mediarecorder.prepare(); 
          mediarecorder.start(); 
          isidle = false; 
          audio_record_start.setbackgroundresource(r.drawable.searchbtn_pressed); 
          timer.schedule(task, 0, 100); 
        } catch (ioexception e) { 
          starttime = 0; 
          log.e(tag, e.tostring()); 
          toast.maketext(audiorecordactivity.this, "录制时发生异常!", toast.length_long).show(); 
        } 
      } 
    }); 
    // 结束录音 
    audio_record_stop.setonclicklistener(new onclicklistener() { 
      @override 
      public void onclick(view v) { 
        if (mediarecorder != null) { 
          stoptime = system.currenttimemillis(); 
          duration = stoptime - starttime; 
          timer.cancel(); 
          mediarecorder.stop(); 
          mediarecorder.release(); 
          mediarecorder = null; 
          audio_record_start.setbackgroundresource(r.drawable.searchbtn_normal); 
          isidle = true; 
        } 
      } 
    }); 
    // 播放录音 
    audio_record_play.setonclicklistener(new onclicklistener() { 
      @override 
      public void onclick(view v) { 
        if (!isidle) { 
          return; 
        } 
 
        if (audio_record_play.gettext().equals("播放录音")) { 
          if (filename == null || filename.equals("") || duration == 0) { 
            toast.maketext(audiorecordactivity.this, "没有录音文件!", toast.length_long).show(); 
            return; 
          } 
 
          try { 
            mediaplayer.reset(); 
            mediaplayer.setdatasource(filename); 
            mediaplayer.prepare(); 
            mediaplayer.start(); 
            isidle = false; 
            audio_record_play.settext("终止播放"); 
            audio_record_play.setbackgroundresource(r.drawable.searchbtn_pressed); 
          } catch (exception e) { 
            e.printstacktrace(); 
            toast.maketext(audiorecordactivity.this, "播放录音时遇到错误!", toast.length_long).show(); 
          } 
        } else { 
          if (mediaplayer != null && mediaplayer.isplaying()) { 
            mediaplayer.stop(); 
            isidle = true; 
          } 
          audio_record_play.settext("播放录音"); 
          audio_record_play.setbackgroundresource(r.drawable.searchinput_bg); 
        } 
      } 
    }); 
    // 确认选择 
    audio_record_select.setonclicklistener(new onclicklistener() { 
      @override 
      public void onclick(view v) { 
        if (filename == null || filename.equals("") || duration == 0) { 
          toast.maketext(audiorecordactivity.this, "没有录音文件!", toast.length_long).show(); 
          return; 
        } 
 
        intent intent = new intent(); 
        intent.putextra("filename", filename); 
        intent.putextra("duration", duration); 
        setresult(success, intent);// 返回成功标识 
        isidle = true; 
        if (mediaplayer != null) { 
          if (mediaplayer.isplaying()) { 
            mediaplayer.stop(); 
          } 
          mediaplayer = null; 
        } 
        finish();// 结束当前的activity,等于点击返回按钮 
      } 
    }); 
  } 
 
  // 捕获返回键,关闭当前页面时返回失败标识 
  @override 
  public boolean onkeydown(int keycode, keyevent event) { 
    if (keycode == keyevent.keycode_back) { 
      setresult(failure); 
      isidle = true; 
      if (mediaplayer != null) { 
        if (mediaplayer.isplaying()) { 
          mediaplayer.stop(); 
        } 
        mediaplayer = null; 
      } 
      finish(); 
      return true; 
    } 
    return super.onkeydown(keycode, event); 
  } 
 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!