【问题标题】:Recording not allow second time不允许第二次录音
【发布时间】:2011-11-03 20:52:41
【问题描述】:

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

这里我附上了 recordign 文件 ::

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;
    }

}

【问题讨论】:

  • 这里需要添加logcat输出
  • 记录器 = 新的 MediaRecorder();在 start() 中添加这一行,让我知道发生了什么?
  • @user370305 AudioRecorder recorder = new AudioRecorder("/audiometer/r");
  • @user370305 我已经更新了我的 listAdapter 文件,请查看
  • 你没有明白我的意思。在您的 AudioRecorder 类的 onStart() 方法中写入 recorder = new MediaRecorder();并仅声明私有 MediaRecorder 记录器;在方法之前的起点。

标签: android


【解决方案1】:

看看这个活动类,检查它与你尝试使用这个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();
 }

}

【讨论】:

  • 这是一个很好的解决方案,谢谢你能详细说明我犯了什么错误吗?
  • @Dr.nik - 你的错误很小,你必须在每次点击列表项时初始化你的 AudioRecorder 类,这样它就变成了新文件,而不是你只做一次初始化,所以你的音频文件被覆盖了。谢谢。
【解决方案2】:

当您尝试再次录制时重新初始化媒体记录器,试试这个更改的代码,

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;
  }

【讨论】:

  • 你用过我上面贴的吗?
  • 抱歉耽搁了。如果媒体记录器停止,则应从媒体记录器释放所有分配的资源。当设置 recorder=null 时,所有资源都会被释放。
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多