录音文件填充

Main文件

package com.gigaset.mediaRecord;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.example.gigaset.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class MediaRecActivity extends Activity implements OnClickListener,
OnItemSelectedListener {


protected static final String tag = "MediaRecActivity";
protected static final int WHAT = 0;


private EditText recordEditText;
private Button addButton;
private Button clearButton;
private ProgressBar progressBar;
private TextView resultTextView;
private Spinner choseSpin;

private TextView norRecTextView ;
// 执行次数
private int COUNTTIME;
// 路径
String RECORDERPATH = Environment.getExternalStorageDirectory().getPath();


MediaRecorder mediaRecorder;


private int progressBarmax; // progressbar 长度
// 数据处理
@SuppressLint("HandlerLeak")
Handler msgHandler = new Handler() {


public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case WHAT:
progressBar.setProgress(progressBarmax - COUNTTIME);
progressBar.setMax(progressBarmax);
Log.i(tag, "WHAT 的intcount-->" + intcount);
resultTextView.setText("总添加数:" + progressBarmax + " 当前执行到:"
+ (progressBarmax - intcount) + "T ");
resultTextView.setTextSize(20);
resultTextView.setGravity(Gravity.CENTER);
if (COUNTTIME == 0) {
resultTextView.append("添加成功");
resultTextView.setTextColor(Color.RED);
startAlarm();
clearButton.setEnabled(true);
}
String string =String.valueOf(msg.obj);
if (choseId==0) {
norRecTextView.setText("普通录音文件数:"+string);
}else {
norRecTextView.setText("电话录音文件数:"+string);
}


break;
default:
break;
}


};


};


boolean isRecord = false;


// 进度条计数器
private int intcount = 0;
// 消息处理
protected Handler threadHandler;


// 选择
private int choseId;


MediaPlayer  mMediaPlayer;


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mediarecord);


findcontrol();
threadHandler = new Handler();


mediaRecorder = new MediaRecorder();


initFile();
//Message msg = new Message();
}



/**铃声*/
private void startAlarm() {  
        mMediaPlayer = MediaPlayer.create(this, getSystemDefultRingtoneUri());  
        mMediaPlayer.setLooping(true);  
        try {  
            mMediaPlayer.prepare();  
        } catch (IllegalStateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        mMediaPlayer.start();  
        try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        mMediaPlayer.stop();
    } 
//获取系统默认铃声的Uri  
    private Uri getSystemDefultRingtoneUri() {  
        return RingtoneManager.getActualDefaultRingtoneUri(this,  
                RingtoneManager.TYPE_RINGTONE);  
    }  

/**返回*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub

if (keyCode==KeyEvent.KEYCODE_BACK) {
MediaRecActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}

File recfFile  ;
File phonerec ;
//查看文件是否存在
private void initFile() {
// TODO Auto-generated method stub
recfFile = new File(RECORDERPATH + "/Recorder/");
if (!recfFile.exists()) {
recfFile.mkdirs();



phonerec = new File(RECORDERPATH + "/PhoneRecord/");
if (!phonerec.exists()) {
phonerec.mkdirs();



}


// 控件
private void findcontrol() {
// TODO Auto-generated method stub
this.recordEditText = (EditText) findViewById(R.id.record_count);


this.addButton = (Button) findViewById(R.id.record_start);
addButton.setOnClickListener(this);


this.clearButton = (Button) findViewById(R.id.record_stop);
clearButton.setOnClickListener(this);


this.progressBar = (ProgressBar) findViewById(R.id.progressBar1);


this.resultTextView = (TextView) findViewById(R.id.record_result);


this.choseSpin = (Spinner) findViewById(R.id.spinner1);
choseSpin.setOnItemSelectedListener(this);

this.norRecTextView = (TextView)findViewById(R.id.recordtext);



}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
threadHandler.removeCallbacks(addRunnable);
MediaRecActivity.this.finish();

super.onDestroy();
}


// add的线程
Runnable addRunnable = new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
Log.e(tag, "addRunnable线程");


Log.e(tag, "COUNTIME-->" + COUNTTIME);
intcount = COUNTTIME - 1;
COUNTTIME = intcount;

if (intcount > -1) {
Log.e(tag, "getpath-->" + RECORDERPATH);


if (choseId == 0) {
copyFilesFassets(
getApplicationContext(),
"Rec.amr",
RECORDERPATH + "/Recorder/"
+ System.currentTimeMillis() + ".amr");
 
 
} else if (choseId == 1) {
copyFilesFassets(
getApplicationContext(),
"phoneRec.amr",
RECORDERPATH + "/PhoneRecord/"
+ System.currentTimeMillis() + ".amr");
}


threadHandler.postDelayed(addRunnable, 1000);


Message msg = new Message();
msg.what = WHAT;
if (choseId==0) {
msg.obj = recfFile.list().length;
}else {
msg.obj = phonerec.list().length;
}

msgHandler.sendMessage(msg);
Log.e(tag, "复制文件完成一次");
return;
}


threadHandler.removeCallbacks(addRunnable);
addButton.setEnabled(true);
}


};



/**
* 从assets目录中复制整个文件夹内容

* @param context
*            Context 使用CopyFiles类的Activity
* @param oldPath
*            String 原文件路径 如:/aa
* @param newPath
*            String 复制后路径 如:xx:/bb/cc
*/
public void copyFilesFassets(Context context, String oldPath, String newPath) {
try {
String fileNames[] = context.getAssets().list(oldPath);// 获取assets目录下的所有文件及目录名
if (fileNames.length > 0) {// 如果是目录
File file = new File(newPath);
file.mkdirs();// 如果文件夹不存在,则递归
for (String fileName : fileNames) {
copyFilesFassets(context, oldPath + "/" + fileName, newPath
+ "/" + fileName);
}
} else {// 如果是文件
InputStream is = context.getAssets().open(oldPath);
FileOutputStream fos = new FileOutputStream(new File(newPath));
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
// buffer字节
fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
}
fos.flush();// 刷新缓冲区
is.close();
fos.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 如果捕捉到错误则通知UI线程


}
}


/** 文件copy */
public void CopyFile(String from, String toString) {


try {
InputStream fosfrom = new FileInputStream(from);
OutputStream fosto = new FileOutputStream(toString);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c);
}
Log.v(tag, "copy ing  ");
fosfrom.close();
fosto.close();


} catch (Exception ex) {
ex.printStackTrace();
}
}


/** 录制文件一次 10s */
@SuppressWarnings("deprecation")
protected void tenrecord() {
// TODO Auto-generated method stub
Log.e(tag, "录制一次,10s");
mediaRecorder.reset();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(RECORDERPATH + "/Recorder/a.amr");
/**
* 调用start开始录音之前,一定要调用prepare方法。
*/
try {
mediaRecorder.prepare();
mediaRecorder.start();
isRecord = true;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


try {
Log.e(tag, "录制中......");
Thread.sleep(11000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


mediaRecorder.stop();
mediaRecorder.release();
Log.e(tag, "录制完成......");


addButton.setEnabled(true);


}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.record_start:
Toast.makeText(getApplicationContext(), "添加录音", Toast.LENGTH_SHORT)
.show();
String recString = recordEditText.getText().toString().trim();
if (recString.equals("")) { // 空
Log.e(tag, "空:" + recString);
COUNTTIME = 1;
progressBarmax = COUNTTIME;
} else { // 非空
Log.e(tag, "非空:" + recString);
COUNTTIME = Integer.parseInt(recString);
progressBarmax = COUNTTIME;
}


// 添加一个输入键盘隐藏
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(getCurrentFocus()
.getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);

threadHandler.postDelayed(addRunnable, 1000);
clearButton.setEnabled(false);
break;
case R.id.record_stop:
if (choseId == 0) {

File recordFile = new File(RECORDERPATH + "/Recorder/");
if (recordFile.exists()) {
DeleteFile(recordFile);
Log.v(tag, "id = 0");
}

recordFile.mkdirs();
norRecTextView.setText("普通录音文件数:0");
resultTextView.setText("删除完成");
Toast.makeText(getApplicationContext(), "普通录音文件夹删除",
Toast.LENGTH_SHORT).show();
} else {
File recordFile1 = new File(RECORDERPATH + "/PhoneRecord/");

if (recordFile1.exists()) {
DeleteFile(recordFile1);
Log.v(tag, "id = 1");
}
recordFile1.mkdirs();
norRecTextView.setText("电话录音文件数:0");
resultTextView.setText("删除完成");
Toast.makeText(getApplicationContext(), "电话录音文件夹删除",
Toast.LENGTH_SHORT).show();
}


break;
default:
break;
}
}


 /**
     * 递归删除文件和文件夹
     * 
     * @param file
     *            要删除的根目录
     */ 
    public void DeleteFile(File file) { 
        if (file.exists() == false) { 
       //     mHandler.sendEmptyMessage(0); 
            return; 
        } else { 
            if (file.isFile()) { 
                file.delete(); 
                return; 
            } 
            if (file.isDirectory()) { 
                File[] childFile = file.listFiles(); 
                if (childFile == null || childFile.length == 0) { 
                    file.delete(); 
                    return; 
                } 
                for (File f : childFile) { 
                    DeleteFile(f); 
                } 
                file.delete(); 
            } 
        } 
    }

/**
* 下拉列表选择监听
* */
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int postion,
long id) {
// TODO Auto-generated method stub
String valString = arg0.getItemAtPosition(postion).toString();


choseId = (int) id;
Log.e(tag, "选择的是:-->" + valString + ";id-->" + choseId);
}


@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub


}


}


XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_count" />


        <EditText
            android:id="@+id/record_count"
            android:layout_width="76dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.14"
            android:ems="10"
            android:inputType="number" >


            <requestFocus />
        </EditText>


        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.13"
            android:text="@string/addtype" />


        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="95dp"
            android:layout_height="match_parent"
            android:layout_weight="0.07"
            android:entries="@array/choose" />


    </LinearLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.53" >


        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="29dp"
            android:orientation="vertical" >


            <Button
                android:id="@+id/record_start"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/add" />


            <Button
                android:id="@+id/record_stop"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/clear" />
        </LinearLayout>


        <TextView
            android:id="@+id/recordtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"  
            android:layout_below="@+id/linearLayout1"
            android:text="普通录音文件数:" />


    </RelativeLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="201dp"
        android:orientation="vertical" >


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.00"
            android:orientation="vertical" >


            <ProgressBar
                android:id="@+id/progressBar1"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="match_parent"
                android:layout_height="34dp"
                android:layout_weight="0.07" />


            <TextView
                android:id="@+id/record_result"
                android:layout_width="match_parent"
                android:layout_height="37dp"
                android:layout_weight="0.10"
                android:textColor="@color/gigasettheme_color"
                android:textSize="16sp" />


        </LinearLayout>


    </LinearLayout>


</LinearLayout>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值