How to convert audio from stereo to mono in Android?

大憨熊 提交于 2019-12-22 01:15:42

问题


I use the android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI intent to load music files from the SD Card.

Intent tmpIntent1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(tmpIntent1, 0);

and in onActivityResult

Uri mediaPath = Uri.parse(data.getData().toString());
MediaPlayer mp = MediaPlayer.create(this, mediaPath);
mp.start();

Now MediaPlayer plays the audio in stereo. Is there any way to convert the selected music/audio file or the output from stereo to mono in the app itself?

I looked up API for SoundPool and AudioTrack, but didn't find how to convert mp3 files audio to mono.

Apps like PowerAMP have those Stereo <-> Mono switches that when pressed immediately convert the output audio to mono signal and back again, how do they do it?


回答1:


Do you load .wav- files respectively PCM- data? If so then you could easily read each sample of each channel, superpose them and divide them by the amount of channels to get a mono signal.

If you store your stereo signal in form of interleaved signed shorts, the code to calculate the resulting mono signal might look like this:

    short[] stereoSamples;//get them from somewhere

    //output array, which will contain the mono signal
    short[] monoSamples= new short[stereoSamples.length/2];
    //length of the .wav-file header-> 44 bytes
    final int HEADER_LENGTH=22;

    //additional counter
    int k=0;


    for(int i=0; i< monoSamples.length;i++){
        //skip the header andsuperpose the samples of the left and right channel
        if(k>HEADER_LENGTH){
        monoSamples[i]= (short) ((stereoSamples[i*2]+ stereoSamples[(i*2)+1])/2);
        }
        k++;
    }

I hope, I was able to help you.

Best regards, G_J



来源:https://stackoverflow.com/questions/17363705/how-to-convert-audio-from-stereo-to-mono-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!