调用录音机并获取生成的文件

时间:2011-07-19 12:16:37

标签: android

我正在尝试使用以下代码在Android 2.2.1(设备Samsung Galaxy POP)上调用录音机:

private static final int ACTIVITY_RECORD_SOUND = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, ACTIVITY_RECORD_SOUND);

这会成功调用录音机。在我的活动结果中,我执行以下操作:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
                         case ACTIVITY_RECORD_SOUND:
                             data.getDataString();
                         break;
                            }
                }
       }

完成录制后,我按回录音机,按预期将控制返回到onActivityResult方法,但我的resultCode始终为0(即Activity.RESULT_CANCELED),我的数据为空。我错过了这里的东西吗?请帮助我。这适用于模拟器,但不适用于设备。提前谢谢。

5 个答案:

答案 0 :(得分:2)

这对我有用:

   @Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
      switch(requestCode) {
         case Flashum.TAKE_MUSIC:
         case Flashum.TAKE_VOICE:
            if (resultCode == Activity.RESULT_OK)
            {
               Log.i(Flashum.LOG_TAG, "onActivityResult got new music");
               Bundle extras = data.getExtras();
               try {
                  Uri u = data.getData();
                  String imageUri;
                  try {
                     imageUri = getRealPathFromURI(u);
                  } catch (Exception ex) {
                     imageUri = u.getPath();
                  }
                  File file = new File(imageUri);
                  FragmentFlash fragmentFlash = (FragmentFlash)mTabsAdapter.getFragment("flash");
                  if (fragmentFlash != null)
                     fragmentFlash.gotMusic(file.getPath());
               } catch (Exception ex) {
                  String s = ex.toString();
                  Log.i(Flashum.LOG_TAG, "onActivityResult " + s);
               }
            }
            else
            {
               Log.i(Flashum.LOG_TAG, "onActivityResult Failed to get music");
            }
            break;
      }
   }

   public String getRealPathFromURI(Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      Cursor cursor = managedQuery(contentUri, proj, null, null, null);
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      cursor.moveToFirst();
      return cursor.getString(column_index);
   }

答案 1 :(得分:0)

我终于通过使用FileObserver找到了解决问题的方法。我通过以下方式实现了它:

package com.pravaa.audiointent;

 import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.Enumeration;
 import java.util.Vector;

 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.FileObserver;
 import android.provider.MediaStore;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.LinearLayout;
 import android.widget.Toast;

public class AudioActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private Button sampleButton;
private FileObserver mFileObserver;
private Vector<String> audioFileNames;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    audioFileNames = new Vector<String>();
    LinearLayout finalContainer = new LinearLayout(this);
    sampleButton = new Button(this);
    sampleButton.setOnClickListener(this);
    sampleButton.setText("Start Audio Intent");
    finalContainer.addView(sampleButton);
    setContentView(finalContainer);
    addObserver();

}

private void addObserver() {
    this.mFileObserver = new FileObserver("/sdcard/Sounds/") {
        @Override
        public void onEvent(int event, String path) {
            if (event == FileObserver.CREATE) {
                if (path != null) {
                    int index = path.indexOf("tmp");
                    String tempFileName = (String) path.subSequence(0,
                            index - 1);
                    audioFileNames.add(tempFileName);

                }
            } else if (event == FileObserver.DELETE) {
                if (path != null) {
                    int index = path.indexOf("tmp");
                    String tempFileName = (String) path.subSequence(0,
                            index - 1);
                    if (audioFileNames.contains(tempFileName)) {
                        audioFileNames.remove(tempFileName);
                    }
                }

            }
        }
    };
}

private void readFile(String fileName) {

    File attachment = new File("/sdcard/Sounds/" + fileName);
    if (attachment.exists()) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(attachment);
            byte[] bytes = new byte[(int) attachment.length()];
            try {
                fis.read(bytes);
                fis.close();

                attachment.delete();

                saveMedia("Test" + fileName, bytes);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

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

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    mFileObserver.startWatching();
}

public void saveMedia(String fileName, byte[] data) {

    String imagePath = "/sdcard/sam/";
    System.out.println("Inside Folder");


    File file = new File(imagePath, fileName);
    System.out.println("File Created");

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
        DataOutputStream dataOutputStream = new DataOutputStream(
                fileOutputStream);
        System.out.println("Writting File");
        dataOutputStream.write(data, 0, data.length);
        System.out.println("Finished writting File");
        dataOutputStream.flush();
        dataOutputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    startActivityForResult(intent, 2); 
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    // TODO Auto-generated method stub
    if (requestCode == 2) {
        if (mFileObserver != null) {
            mFileObserver.stopWatching();
        }
        Enumeration<String> audioFileEnum = audioFileNames.elements();
        while (audioFileEnum.hasMoreElements()) {
            readFile((String) audioFileEnum.nextElement());
        }
    }
}}

答案 2 :(得分:0)

我面临同样的问题..所以我没有使用意图,而是使用了MediaRecorder类及其相关的方法,如setAudioEncoder,setAudioSource,prepare,start,stop,setOutputFormat和setOutputFile ..现在工作正常.. < / p>

答案 3 :(得分:0)

我也同意目前为止的最佳答案(由问题所有者投票),但它无法读取文件,因为它是一条不同的路径。我的建议是将文件名存储为成员变量,只调用一次getFilename()。

答案 4 :(得分:-4)

Galaxy Android设备存在一个已知问题,即结果意图为空,您希望它们包含照片。这也可能适用于此。请参阅http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/

解决此问题的一种方法是添加

intent.putExtra(MediaStore.EXTRA_OUTPUT, someFileUri);

根据您的意图,明确告知目标应用程序存储生成的文件的位置。

如果您需要帮助创建一个好的文件Uri,请查看此example