如何拦截Android设备上的音频流?

时间:2010-07-08 11:10:37

标签: java c++ android

让我们假设我们有以下场景:某些东西正在Android设备上播放(一个mp3的例子,但它可能是任何使用Android设备的音频部分的东西)。从一个应用程序(Android应用程序:)),我想拦截音频流来分析它,记录它,等等。从这个应用程序(让我们说“分析器”)我不想启动一个MP3或东西,我想要的只是访问android的音频流。

感谢任何建议,它可以是Java或C ++解决方案。

2 个答案:

答案 0 :(得分:1)

http://developer.android.com/reference/android/media/MediaRecorder.html

    public class AudioRecorder {

    final MediaRecorder recorder = new MediaRecorder();
    final String path;

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

    private String sanitizePath(String path) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        if (!path.contains(".")) {
            path += ".3gp";
        }
        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.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)

如果要获取特定应用的音频流,请考虑使用Android 10中引入的AudioPlaybackCapture API