录音不允许第二次

时间:2011-11-03 10:13:07

标签: android

我开发录制音频应用程序,其中录制存储在sdcard.i第一次获得成功录制声音但是(如点击录制按钮开始录制并点击停止按钮它将停止)现在问题是第二次提出。如果我点击记录按钮,它将退出应用程序。

我已附上 recordign file ::

package com.SaxParser2;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import android.media.MediaRecorder;
import android.os.Environment;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


 public class AudioRecorder {

  final MediaRecorder recorder = new MediaRecorder();
  final String path;
  final Random myRandom = new Random();
  String currentDateTimeString = DateFormat.getDateInstance().format(new Date());



  /**
   * Creates a new audio recording at the given path (relative to root of SD card).
   */
  public AudioRecorder(String path) {
    this.path = sanitizePath(path);

  }

  public String sanitizePath(String path) {
    if (!path.startsWith("/")) {
      path = "/" + path;
    }
    if (!path.contains(".")) {
         Calendar c = Calendar.getInstance();
         System.out.println("Current time => "+c.getTime());
         int  strHour = c.get(Calendar.HOUR);
         int strSecond = c.get(Calendar.SECOND);
         int strMinute = c.get(Calendar.MINUTE);
         int strMonth  = c.get(Calendar.MONTH);
         int strYear = c.get(Calendar.YEAR);
         int strDay = c.get(Calendar.DAY_OF_MONTH);
      path += String.valueOf(myRandom.nextInt())+""+strSecond+strMinute+strDay+strMonth+strYear+".mp3";
    }
    return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
  }

  /**
   * Starts a new recording.
   */
  public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
    throw new IOException("SD Card is not mounted.  It is " + state + ".");
}

// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
  throw new IOException("Path to file could not be created.");
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}

  /**
   * Stops a recording that has been previously started.
   */
  public void stop() throws IOException {

    recorder.stop();
    recorder.release();
  }

}

**ListAdapter  ::** 

    package com.SaxParser2;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewAdapter extends BaseAdapter {
    Activity context;
    String title[];
    String description[];

    AudioRecorder recorder;// = new AudioRecorder("/audiometer/r");

    private static String mFileName = null;
    private MediaRecorder mRecorder = null;
    private MediaPlayer mPlayer = null;

    public ListViewAdapter(Activity context, String[] title,
            String[] description) {
        super();
        this.context = context;
        this.title = title;
        this.description = description;

    }

    public int getCount() {
        // TODO Auto-generated method stub
        return title.length;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    private class ViewHolder {
        TextView txtViewTitle;
        TextView txtViewDescription;
        Button record, stop;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder holder;
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listitem_row, null);
            holder = new ViewHolder();
            holder.txtViewTitle = (TextView) convertView
                    .findViewById(R.id.textView1);
            holder.txtViewDescription = (TextView) convertView
                    .findViewById(R.id.textView2);
            holder.record = (Button) convertView.findViewById(R.id.record);
            holder.stop = (Button) convertView.findViewById(R.id.stop);
            recorder = new AudioRecorder("/audiometer/r"+ position);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        try {
            holder.txtViewTitle.setText(title[position]);
            holder.txtViewDescription.setText(description[position]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        holder.record.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                try {

                    recorder.start();

                } catch (IOException e) {
                    Writer writer = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(writer);
                    e.printStackTrace(printWriter);
                    String s = writer.toString();
                    Toast.makeText(context, s, Toast.LENGTH_LONG).show();
                }

            }
        });
        holder.stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {

                    recorder.stop();

                } catch (IOException e) {
                    Writer writer = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(writer);
                    e.printStackTrace(printWriter);
                    String s = writer.toString();
                    Toast.makeText(context, s, Toast.LENGTH_LONG).show();

                }
            }
        });
        return convertView;
    }

}

2 个答案:

答案 0 :(得分:2)

查看此活动类,检查代码与尝试使用此 ListViewAdapter:

的不同之处
public class ListViewAdapter extends BaseAdapter {
Activity context;
String title[];
String description[];

AudioRecorder recorder; // here I made changes......

private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;

public ListViewAdapter(Activity context, String[] title,
        String[] description) {
    super();
    this.context = context;
    this.title = title;
    this.description = description;

}

public int getCount() {
    // TODO Auto-generated method stub
    return title.length;
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

private class ViewHolder {
    TextView txtViewTitle;
    TextView txtViewDescription;
    Button record, stop;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder holder;
    LayoutInflater inflater = context.getLayoutInflater();

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.listitem_row, null);
        holder = new ViewHolder();
        holder.txtViewTitle = (TextView) convertView
                .findViewById(R.id.textView1);
        holder.txtViewDescription = (TextView) convertView
                .findViewById(R.id.textView2);
        holder.record = (Button) convertView.findViewById(R.id.record);
        holder.stop = (Button) convertView.findViewById(R.id.stop);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    try {
        holder.txtViewTitle.setText(title[position]);
        holder.txtViewDescription.setText(description[position]);
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    }
    holder.record.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {
                recorder = new AudioRecorder("/audiometer/r"+ position); // here I made changes......
                recorder.start();

            } catch (IOException e) {
                Writer writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                e.printStackTrace(printWriter);
                String s = writer.toString();
                Toast.makeText(context, s, Toast.LENGTH_LONG).show();
            }

        }
    });
    holder.stop.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {

                recorder.stop();

            } catch (IOException e) {
                Writer writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                e.printStackTrace(printWriter);
                String s = writer.toString();
                Toast.makeText(context, s, Toast.LENGTH_LONG).show();

            }
        }
    });
    return convertView;
 }

}

您的AudioRecorder课程:

package com.SaxParser2;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import android.media.MediaRecorder;
import android.os.Environment;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


public class AudioRecorder {

  private MediaRecorder recorder; // here I made changes......
  private String path;
  private Random myRandom = new Random();
  String currentDateTimeString = DateFormat.getDateInstance().format(new Date());



  /**
   * Creates a new audio recording at the given path (relative to root of SD card).
   */
  public AudioRecorder(String path) {
    this.path = sanitizePath(path);

  }

  public String sanitizePath(String path) {
    if (!path.startsWith("/")) {
      path = "/" + path;
    }
    if (!path.contains(".")) {
         Calendar c = Calendar.getInstance();
         System.out.println("Current time => "+c.getTime());
         int  strHour = c.get(Calendar.HOUR);
         int strSecond = c.get(Calendar.SECOND);
         int strMinute = c.get(Calendar.MINUTE);
         int strMonth  = c.get(Calendar.MONTH);
         int strYear = c.get(Calendar.YEAR);
         int strDay = c.get(Calendar.DAY_OF_MONTH);
      path += String.valueOf(myRandom.nextInt())+""+strSecond+strMinute+strDay+strMonth+strYear+".mp3";
    }
    return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
  }

  /**
   * Starts a new recording.
   */
  public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
    throw new IOException("SD Card is not mounted.  It is " + state + ".");
}

// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
  throw new IOException("Path to file could not be created.");
}
recorder = new MediaRecorder(); // here I made changes......
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}

/**
 * Stops a recording that has been previously started.
 */
 public void stop() throws IOException {

  recorder.stop();
  recorder.release();
 }

}

答案 1 :(得分:1)

当您再次尝试录制时重新初始化媒体编码器,尝试更改此代码,

public void start() throws IOException {
    String state = android.os.Environment.getExternalStorageState();
    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
        throw new IOException("SD Card is not mounted.  It is " + state + ".");
    }

    // make sure the directory we plan to store the recording in exists
    File directory = new File(path).getParentFile();
    if (!directory.exists() && !directory.mkdirs()) {
      throw new IOException("Path to file could not be created.");
    }
    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(path);
    recorder.prepare();
    recorder.start();
  }

  /**
   * Stops a recording that has been previously started.
   */
  public void stop() throws IOException {
    recorder.stop();
    recorder.release();
    recorder=null;
  }