【问题标题】:Talking App like talking tom, Audio Recording didn't work on all devices像会说话的汤姆猫一样的会说话的应用程序,录音不适用于所有设备
【发布时间】:2015-06-14 13:59:48
【问题描述】:

我正在开发像会说话的汤姆这样的应用程序,一切正常,只是在某些设备上出现录音问题,音频在我的 hdpi 设备上也可以正常工作,但每当我在三星 tab 7 或 tab 10 或任何设备上运行它时其他手机,在某些设备上它会持续收听音频,而在某些设备上根本不听,我正在使用以下代码进行录音。

private int RECORDER_CHANNELS = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private int RECORDER_SAMPLERATE = 44100;
private byte RECORDER_BPP = (byte) 16;
private AudioRecord audioRecorder;
private int detectVoice= 350;

public class analyzeAudio extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        Log.e("Play", "on Pre");

    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {
            // Get the minimum buffer size required for the successful creation of an AudioRecord object.
            int bufferSizeInBytes = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                    RECORDER_AUDIO_ENCODING);

            bufferSizeInBytes = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
            // Initialize Audio Recorder.
            audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE,
                    RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSizeInBytes);

            // Start Recording.
            audioRecorder.startRecording();

            int numberOfReadBytes = 0;
            byte audioBuffer[] = new byte[bufferSizeInBytes];
            boolean recording = false;
            float tempFloatBuffer[] = new float[3];
            int tempIndex = 0;
            int totalReadBytes = 0;
            byte totalByteBuffer[] = new byte[60 * 44100 * 2];

            // While data come from microphone.
            boolean isListening = true;
            while (true) {
                float totalAbsValue = 0.0f;
                short sample = 0;

                numberOfReadBytes = audioRecorder.read(audioBuffer, 0, bufferSizeInBytes);

                // Analyze Sound.
                for (int i = 0; i < bufferSizeInBytes; i += 2) {
                    sample = (short) ((audioBuffer[i]) | audioBuffer[i + 1] << 8);
                    totalAbsValue += Math.abs(sample) / (numberOfReadBytes / 2);
                }

                // Analyze temp buffer.
                tempFloatBuffer[tempIndex % 3] = totalAbsValue;
                float temp = 0.0f;
                for (int i = 0; i < 3; ++i)
                    temp += tempFloatBuffer[i];

                if ((temp >= 0 && temp <= detectVoice) && recording == false) {
                    Log.i("TAG", "1");
                    tempIndex++;
                    continue;
                }

                if (temp > detectVoice && recording == false) {
                    Log.i("TAG", "2");
                    if (isPlaying) {
                        audioRecorder.release();
                        break;
                    }
                    recording = true;

                    if (isListening) {
                        finishIdleAnimation();
                        isListening = false;
                        isPlaying = true;
                        currentAnimationId = Constants.animHearout;
                        _index = 0;
                        if (_timer != null) {
                            _timer.cancel();
                        }
                        _timer = new Timer();
                        _timer.schedule(new TickClass(), 7, dealyTime(7, 1));

                    } else {
                        Log.e("Caceling", "Yes + isPlaying" + isPlaying);
                        new analyzeAudio().cancel(true);
                    }
                }

                if ((temp >= 0 && temp <= detectVoice) && recording == true) {
                    Log.i("TAG", "Save audio to file.");

                    // Save audio to file.
                    String filepath = Environment.getExternalStorageDirectory().getPath();
                    File file = new File(filepath, "AudioRecorder");
                    if (!file.exists())
                        file.mkdirs();

                    String fn = file.getAbsolutePath() + "/" + "temp" + ".wav";
                    long totalAudioLen = 0;
                    long totalDataLen = totalAudioLen + 36;
                    long longSampleRate = RECORDER_SAMPLERATE;
                    int channels = 1;
                    long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8;
                    totalAudioLen = totalReadBytes;
                    totalDataLen = totalAudioLen + 36;
                    byte finalBuffer[] = new byte[totalReadBytes + 44];

                    finalBuffer[0] = 'R'; // RIFF/WAVE header
                    finalBuffer[1] = 'I';
                    finalBuffer[2] = 'F';
                    finalBuffer[3] = 'F';
                    finalBuffer[4] = (byte) (totalDataLen & 0xff);
                    finalBuffer[5] = (byte) ((totalDataLen >> 8) & 0xff);
                    finalBuffer[6] = (byte) ((totalDataLen >> 16) & 0xff);
                    finalBuffer[7] = (byte) ((totalDataLen >> 24) & 0xff);
                    finalBuffer[8] = 'W';
                    finalBuffer[9] = 'A';
                    finalBuffer[10] = 'V';
                    finalBuffer[11] = 'E';
                    finalBuffer[12] = 'f'; // 'fmt ' chunk
                    finalBuffer[13] = 'm';
                    finalBuffer[14] = 't';
                    finalBuffer[15] = ' ';
                    finalBuffer[16] = 16; // 4 bytes: size of 'fmt ' chunk
                    finalBuffer[17] = 0;
                    finalBuffer[18] = 0;
                    finalBuffer[19] = 0;
                    finalBuffer[20] = 1; // format = 1
                    finalBuffer[21] = 0;
                    finalBuffer[22] = (byte) channels;
                    finalBuffer[23] = 0;
                    finalBuffer[24] = (byte) (longSampleRate & 0xff);
                    finalBuffer[25] = (byte) ((longSampleRate >> 8) & 0xff);
                    finalBuffer[26] = (byte) ((longSampleRate >> 16) & 0xff);
                    finalBuffer[27] = (byte) ((longSampleRate >> 24) & 0xff);
                    finalBuffer[28] = (byte) (byteRate & 0xff);
                    finalBuffer[29] = (byte) ((byteRate >> 8) & 0xff);
                    finalBuffer[30] = (byte) ((byteRate >> 16) & 0xff);
                    finalBuffer[31] = (byte) ((byteRate >> 24) & 0xff);
                    finalBuffer[32] = (byte) (2 * 16 / 8); // block align
                    finalBuffer[33] = 0;
                    finalBuffer[34] = RECORDER_BPP; // bits per sample
                    finalBuffer[35] = 0;
                    finalBuffer[36] = 'd';
                    finalBuffer[37] = 'a';
                    finalBuffer[38] = 't';
                    finalBuffer[39] = 'a';
                    finalBuffer[40] = (byte) (totalAudioLen & 0xff);
                    finalBuffer[41] = (byte) ((totalAudioLen >> 8) & 0xff);
                    finalBuffer[42] = (byte) ((totalAudioLen >> 16) & 0xff);
                    finalBuffer[43] = (byte) ((totalAudioLen >> 24) & 0xff);

                    for (int i = 0; i < totalReadBytes; ++i)
                        finalBuffer[44 + i] = totalByteBuffer[i];

                    FileOutputStream out;
                    try {
                        out = new FileOutputStream(fn);
                        try {
                            out.write(finalBuffer);
                            out.close();
                            isRecorded = true;
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }


                    tempIndex++;
                    break;
                }

                // -> Recording sound here.
                Log.i("TAG", "Recording Sound.");
                for (int i = 0; i < numberOfReadBytes; i++)
                    totalByteBuffer[totalReadBytes + i] = audioBuffer[i];
                totalReadBytes += numberOfReadBytes;

                tempIndex++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {

        Log.e("Play", "on POst");
        if (isRecorded) {
            currentAnimationId = Constants.animHearoutend;
            _index = 8;
            if (_timer != null) {
                _timer.cancel();
            }
            _timer = new Timer();
            _timer.schedule(new TickClass(), 4, dealyTime(4, 1));
            playFromSdCard();
        }
    }
}

【问题讨论】:

  • 在哪些设备上出现故障?您是否调试过故障设备或从故障设备获取日志?
  • 我只是想知道您的录制对象是否正在初始化?
  • 是的,它确实是,它适用于 hdpi 设备 QMobile,但是当我在三星 s4 上运行时,它会持续监听并且不会停止监听,而对于三星标签 2、7'' 它不是完全在听。
  • @arslanhaktic 默认录音机中的正常录音是否工作正常?
  • @PreethiRao 感谢您的关注,但它在一台设备上运行良好,如果我更改其从其他设备听到的声音的值。所以我不认为这是由于同一线程造成的问题。

标签: android audio audio-recording mobile-application voice-recording


【解决方案1】:

输入此代码以检查您的设备是否支持采样率和音频格式。检查组合,看看哪个适合你

private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };

    for (int rate : mSampleRates) {
                for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT,AudioFormat.ENCODING_PCM_16BIT }) {
                    for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
                        try {
                            Log.d(TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
                                    + channelConfig);
                            int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

                            if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                                Log.d(TAG, "Found rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
                                        + channelConfig);

                      Log.d(TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
                                    + channelConfig +" supported");


                            }
                        } catch (Exception e) {
                            Log.e(TAG, rate + "Exception, keep trying.",e);
                        }
                    }
                }
            }

【讨论】:

  • 感谢您的回答,但它找到了所有采样率。现在我很困惑在这四个中使用哪一个。你能详细说明一下吗?谢谢
  • 是的,它适用于所有采样率,这意味着它支持所有采样率,采样率越大质量越好。你可以使用任何你想要的。我只是让您了解设备是否支持采样率
【解决方案2】:

代码并没有真正检查错误情况,这使得找出这些设备上的问题变得更加困难。 请执行以下操作:

  1. 与录音(但播放)无关,但如果您注意 AudioFocus 会更好。它可能会丢失等。您需要知道的都在这里http://developer.android.com/training/managing-audio/audio-focus.html
  2. 添加对 AudioRecord.getState() 的调用以验证状态
  3. 添加调用 AudioRecord.getRecordingState() 来验证录音状态
  4. 在 getMinBufferSize 中,您需要检查 ERROR_BAD_VALUE
  5. 在读取调用中,您需要检查 ERROR_INVALID_OPERATION 和 ERROR_BAD_VALUE
  6. 您可以使用 setRecordPositionUpdateListener 来判断录制是否已进行。

这些步骤 + 观察系统 logcat 将使您能够更好地查明问题或为我们提供解决问题的信息

【讨论】:

    【解决方案3】:

    如果您在不支持的设备上强制使用任意采样率,您将会遇到麻烦。

    我建议您检查并为正在运行的设备设置一个有效的采样率(而不是将其硬编码为 44.1Khz)。

    查看here,了解有关如何检查可用采样率的一些提示。

    【讨论】:

    • 我尝试点击您提供的链接。我已经相应地编写了上面的代码(我将该代码添加到问题本身)。但是还是不行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多