How can I intercept the audio stream on an android device?

后端 未结 2 1273
小蘑菇
小蘑菇 2021-02-13 15:42

Let\'s suppose that we have the following scenario: something is playing on an android device (an mp3 par example, but it could be anything that use the audio part of an android

相关标签:
2条回答
  • 2021-02-13 16:17

    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();
        }
    }
    
    0 讨论(0)
  • 2021-02-13 16:19

    Consider using the AudioPlaybackCapture API that was introduced in Android 10 if you want to get the audio stream for a particular app.

    0 讨论(0)
提交回复
热议问题