2011-11-03 3 views
0

Я разрабатываю звуковое приложение для записи, в котором запись хранится в sdcard.i в первый раз звучит звук записи, но (например, нажмите кнопку записи, запишите запись и нажмите кнопку остановки, это остановится) теперь проблема возникает второй раз. Вэнь я нажимаю на кнопку записи, она выйдет из приложения.Запись не разрешена во второй раз

Здесь я есть присоединять 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; 
    } 

} 
+0

Вам нужно добавить вывод LogCat здесь – Reno

+0

магнитофона = новый MediaRecorder(); добавьте эту строку в start() и сообщите мне, что произойдет? – user370305

+0

@ user370305 'AudioRecorder recorder = новый AudioRecorder ("/audiometer/r ");' –

ответ

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

} 
+0

его действительно хорошая помощь. ты можешь поговорить завтра? –

+0

Это хорошее решение, спасибо, можете ли вы уточнить, что такое ошибка, сделанная мной? –

+0

@ Dr.nik - Ваша ошибка была небольшой. Вы должны инициализировать свой класс AudioRecorder при каждом щелчке списка, чтобы он стал новым, вместо этого вы делали только один раз, чтобы инициализировать, чтобы ваш аудиофайл был перезаписан. Благодарю. – user370305

1

Re инициализации СМИ перекодировщик, когда вы пытаетесь записать снова, попробуйте этот код изменен,

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

Можете ли вы подробно рассказать об этом? –

+0

Вы использовали выше, которое я разместил? –

+0

очевидно ... , ... –

Смежные вопросы