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

2022-09-04 23:28:17

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

任何建议都是值得赞赏的,它可以是Java或C++解决方案。


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

答案 2

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


推荐