Android Visualizer 实现崩溃

发布于 2024-12-22 06:43:09 字数 2196 浏览 2 评论 0原文

我正在尝试实现 Android Visualizer 类。我已经查找了其他问题线程,但仍然遇到致命错误。在我看来,这一切都应该正常工作,无论出于何种原因 AVD 不断崩溃。

首先,我使用权限:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

这是我的 logcat:

12-21 15:10:46.983: D/dalvikvm(642): Not late-enabling CheckJNI (already on)
12-21 15:10:48.823: D/MediaPlayer(642): Couldn't open file on client side, trying server     side  
12-21 15:10:53.603: E/AudioEffect(642): set(): AudioFlinger could not create effect,    status: -22
12-21 15:10:53.603: E/visualizers-JNI(642): Visualizer initCheck failed -4
12-21 15:10:53.613: E/Visualizer-JAVA(642): Error code -4 when initializing Visualizer.
12-21 15:10:53.613: E/Visual Ex(642): Cannot initialize Visualizer engine, error: -4
12-21 15:10:53.964: D/gralloc_goldfish(642): Emulator without GPU emulation detected.

和我的代码:

package MediaPlayer.namespace;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.audiofx.Visualizer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class MediaPlayerActivity extends Activity 
{
Visualizer      visual;
int             formattedVizData[];
byte            rawWaveForm[];
int             cont = 0xFF;

public void onCreate(Bundle savedInstanceState) 
{
    //start
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    ///start media player & visualizer.
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
    mediaPlayer.start();
    // Create the Visualizer object and attach it to our media player.
    try{
        visual = new Visualizer(mediaPlayer.getAudioSessionId()); // this line causing Exception 
        visual.setEnabled(true);
        visual.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
        }
        catch(Exception ex)
        {
            Log.e("Visual Ex", ex.getMessage());
        }
    }
}

I am trying to implement the Android Visualizer class. I have looked up other trouble threads but I am still getting a fatal error. This all looks to me like it should work correctly, for whatever reason the AVD keeps on crashing.

First off, I am using the permissions:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

Here is my logcat:

12-21 15:10:46.983: D/dalvikvm(642): Not late-enabling CheckJNI (already on)
12-21 15:10:48.823: D/MediaPlayer(642): Couldn't open file on client side, trying server     side  
12-21 15:10:53.603: E/AudioEffect(642): set(): AudioFlinger could not create effect,    status: -22
12-21 15:10:53.603: E/visualizers-JNI(642): Visualizer initCheck failed -4
12-21 15:10:53.613: E/Visualizer-JAVA(642): Error code -4 when initializing Visualizer.
12-21 15:10:53.613: E/Visual Ex(642): Cannot initialize Visualizer engine, error: -4
12-21 15:10:53.964: D/gralloc_goldfish(642): Emulator without GPU emulation detected.

And my code:

package MediaPlayer.namespace;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.audiofx.Visualizer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class MediaPlayerActivity extends Activity 
{
Visualizer      visual;
int             formattedVizData[];
byte            rawWaveForm[];
int             cont = 0xFF;

public void onCreate(Bundle savedInstanceState) 
{
    //start
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    ///start media player & visualizer.
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
    mediaPlayer.start();
    // Create the Visualizer object and attach it to our media player.
    try{
        visual = new Visualizer(mediaPlayer.getAudioSessionId()); // this line causing Exception 
        visual.setEnabled(true);
        visual.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
        }
        catch(Exception ex)
        {
            Log.e("Visual Ex", ex.getMessage());
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小镇女孩 2024-12-29 06:43:09

我有同样的问题,所以尝试添加

AndroidManifest.xml 文件中的权限

另外,如果您不想看到奥迪波形,您应该在画布或其他东西中显示它...

工作示例:

//android.permission.MODIFY_AUDIO_SETTINGS for audio settings and also
//android.permission.INTERNET for internet streaming

package com.janilemy;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

public class AudioFxDemoActivity extends Activity {

    //Here is your URL defined
String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";

    //Constants for vizualizator - HEIGHT 50dip
private static final float VISUALIZER_HEIGHT_DIP = 50f;

    //Your MediaPlayer
MediaPlayer mp;

//Vizualization
private Visualizer mVisualizer;

    private LinearLayout mLinearLayout;
    private VisualizerView mVisualizerView;
    private TextView mStatusTextView;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Info textView
    mStatusTextView = new TextView(this);

    //Create new LinearLayout ( because main.xml is empty )
    mLinearLayout = new LinearLayout(this);
    mLinearLayout.setOrientation(LinearLayout.VERTICAL);
    mLinearLayout.addView(mStatusTextView);

    //set content view to new Layout that we create
    setContentView(mLinearLayout);

    //start media player - like normal
    mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        mp.setDataSource(url); // set data source our URL defined
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    try {   //tell your player to go to prepare state
        mp.prepare(); 
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
            //Start your stream / player
    mp.start();

    //setup your Vizualizer - call method
    setupVisualizerFxAndUI();        

            //enable vizualizer
            mVisualizer.setEnabled(true);

            //Info text
    mStatusTextView.setText("Playing audio...");
}

    //Our method that sets Vizualizer
private void setupVisualizerFxAndUI() {
    // Create a VisualizerView (defined below), which will render the simplified audio
    // wave form to a Canvas.

    //You need to have something where to show Audio WAVE - in this case Canvas
    mVisualizerView = new VisualizerView(this);
    mVisualizerView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density)));
    mLinearLayout.addView(mVisualizerView);

    // Create the Visualizer object and attach it to our media player.
    //YOU NEED android.permission.RECORD_AUDIO for that in AndroidManifest.xml
    mVisualizer = new Visualizer(mp.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
        public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
                int samplingRate) {
            mVisualizerView.updateVisualizer(bytes);
        }

        public void onFftDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) {}
    }, Visualizer.getMaxCaptureRate() / 2, true, false); 
}

@Override
protected void onPause() {
    super.onPause();

    if (isFinishing() && mp != null) {
        mVisualizer.release();
        mEqualizer.release();
        mp.release();
        mp = null;
    }
}

/**
 * A simple class that draws waveform data received from a
 * {@link Visualizer.OnDataCaptureListener#onWaveFormDataCapture }
 */
class VisualizerView extends View {
    private byte[] mBytes;
    private float[] mPoints;
    private Rect mRect = new Rect();

    private Paint mForePaint = new Paint();

    public VisualizerView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mBytes = null;

        mForePaint.setStrokeWidth(1f);
        mForePaint.setAntiAlias(true);
        mForePaint.setColor(Color.rgb(0, 128, 255));
    }

    public void updateVisualizer(byte[] bytes) {
        mBytes = bytes;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mBytes == null) {
            return;
        }

        if (mPoints == null || mPoints.length < mBytes.length * 4) {
            mPoints = new float[mBytes.length * 4];
        }

        mRect.set(0, 0, getWidth(), getHeight());

        for (int i = 0; i < mBytes.length - 1; i++) {
            mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
            mPoints[i * 4 + 1] = mRect.height() / 2
                    + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
            mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
            mPoints[i * 4 + 3] = mRect.height() / 2
                    + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2) / 128;
        }

        canvas.drawLines(mPoints, mForePaint);
    }
}

}

这是 Android 媒体播放器音频波形可视化的完整工作示例...我希望它能帮助您解决问题...

Jani L

I have same problem, so try to add

permission in AndroidManifest.xml file

Also if you wan`t to see that audi wave, you hould show it in canvas or something ...

Working example :

//android.permission.MODIFY_AUDIO_SETTINGS for audio settings and also
//android.permission.INTERNET for internet streaming

package com.janilemy;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

public class AudioFxDemoActivity extends Activity {

    //Here is your URL defined
String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";

    //Constants for vizualizator - HEIGHT 50dip
private static final float VISUALIZER_HEIGHT_DIP = 50f;

    //Your MediaPlayer
MediaPlayer mp;

//Vizualization
private Visualizer mVisualizer;

    private LinearLayout mLinearLayout;
    private VisualizerView mVisualizerView;
    private TextView mStatusTextView;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Info textView
    mStatusTextView = new TextView(this);

    //Create new LinearLayout ( because main.xml is empty )
    mLinearLayout = new LinearLayout(this);
    mLinearLayout.setOrientation(LinearLayout.VERTICAL);
    mLinearLayout.addView(mStatusTextView);

    //set content view to new Layout that we create
    setContentView(mLinearLayout);

    //start media player - like normal
    mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        mp.setDataSource(url); // set data source our URL defined
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    try {   //tell your player to go to prepare state
        mp.prepare(); 
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
            //Start your stream / player
    mp.start();

    //setup your Vizualizer - call method
    setupVisualizerFxAndUI();        

            //enable vizualizer
            mVisualizer.setEnabled(true);

            //Info text
    mStatusTextView.setText("Playing audio...");
}

    //Our method that sets Vizualizer
private void setupVisualizerFxAndUI() {
    // Create a VisualizerView (defined below), which will render the simplified audio
    // wave form to a Canvas.

    //You need to have something where to show Audio WAVE - in this case Canvas
    mVisualizerView = new VisualizerView(this);
    mVisualizerView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density)));
    mLinearLayout.addView(mVisualizerView);

    // Create the Visualizer object and attach it to our media player.
    //YOU NEED android.permission.RECORD_AUDIO for that in AndroidManifest.xml
    mVisualizer = new Visualizer(mp.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
        public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
                int samplingRate) {
            mVisualizerView.updateVisualizer(bytes);
        }

        public void onFftDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) {}
    }, Visualizer.getMaxCaptureRate() / 2, true, false); 
}

@Override
protected void onPause() {
    super.onPause();

    if (isFinishing() && mp != null) {
        mVisualizer.release();
        mEqualizer.release();
        mp.release();
        mp = null;
    }
}

/**
 * A simple class that draws waveform data received from a
 * {@link Visualizer.OnDataCaptureListener#onWaveFormDataCapture }
 */
class VisualizerView extends View {
    private byte[] mBytes;
    private float[] mPoints;
    private Rect mRect = new Rect();

    private Paint mForePaint = new Paint();

    public VisualizerView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mBytes = null;

        mForePaint.setStrokeWidth(1f);
        mForePaint.setAntiAlias(true);
        mForePaint.setColor(Color.rgb(0, 128, 255));
    }

    public void updateVisualizer(byte[] bytes) {
        mBytes = bytes;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mBytes == null) {
            return;
        }

        if (mPoints == null || mPoints.length < mBytes.length * 4) {
            mPoints = new float[mBytes.length * 4];
        }

        mRect.set(0, 0, getWidth(), getHeight());

        for (int i = 0; i < mBytes.length - 1; i++) {
            mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
            mPoints[i * 4 + 1] = mRect.height() / 2
                    + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
            mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
            mPoints[i * 4 + 3] = mRect.height() / 2
                    + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2) / 128;
        }

        canvas.drawLines(mPoints, mForePaint);
    }
}

}

This is a full working example of android media player audio wave visualization... I hope it will help you with your solution ...

Jani L

春夜浅 2024-12-29 06:43:09

使用 Visualizer 有一些重要的事情。

  1. 最低api级别必须等于或大于9。
  2. Visualizer引擎,错误:-1表示RECORD_AUDIO权限
    丢失的。
  3. Visualizer 引擎,错误:-4 表示由于参数错误而操作失败。价值。展示台的配置有问题,您没有正确设置展示台。

另请参阅我的此处的答案

注意

参数 (audioSession) 系统范围内唯一的音频会话标识符。如果audioSession不为0,则可视化器将附加到同一音频会话中的MediaPlayer或AudioTrack。否则,Visualizer 将应用于输出混合。

There are some important things for using Visualizer.

  1. minimum api level must be equal to or greater than 9.
  2. Visualizer engine, error: -1 means RECORD_AUDIO permission is
    missing.
  3. Visualizer engine, error: -4 means Operation failed due to bad parameter. value. something bad in the configuration of the Visualizer, you don't properly setup Visualizer.

And also see my answer here.

Note

Parameters (audioSession) system wide unique audio session identifier. If audioSession is not 0, the visualizer will be attached to the MediaPlayer or AudioTrack in the same audio session. Otherwise, the Visualizer will apply to the output mix.

太阳哥哥 2024-12-29 06:43:09

@Kaushal28、@ihsan、gaozp、@Big Money

-3 错误代码表示 ERROR_NO_INIT
注意: https://developer.android.com/reference/kotlin/ android/media/audiofx/Visualizer

我有同样的经历并使用了AudioRecorder的audioSessionId。

如果你检查Visualizer的文档,你只能使用MediaPlayer和AudioTrack,如下所示。

If audioSession is not 0, the visualizer will be attached to the 
MediaPlayer or AudioTrack in the same audio session. Otherwise, 
the Visualizer will apply to the output mix.

@Kaushal28, @ihsan,gaozp, @Big Money

-3 error code means ERROR_NO_INIT
Note: https://developer.android.com/reference/kotlin/android/media/audiofx/Visualizer

I had the same experience and used the AudioRecorder's audioSesstionId.

If you check the documentation of Visualizer, you can use only MediaPlayer and AudioTrack as shown below.

If audioSession is not 0, the visualizer will be attached to the 
MediaPlayer or AudioTrack in the same audio session. Otherwise, 
the Visualizer will apply to the output mix.
哭泣的笑容 2024-12-29 06:43:09

您缺少互联网权限

<uses-permission android:name="android.permission.INTERNET" />

You are missing Internet permission

<uses-permission android:name="android.permission.INTERNET" />
深海夜未眠 2024-12-29 06:43:09

启用 Visulizer 后,您无法对它的对象进行任何更改。因此,只需交换到如亲爱的代码所示的行即可。

public class MediaPlayerActivity extends Activity {

    Visualizer visual;
    int formattedVizData[];
    byte rawWaveForm[];
    int cont = 0xFF;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Start media player & visualizer.
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
        mediaPlayer.start();

        // Create the Visualizer object and attach it to our media player.
        try {

            // this line is not actually causing Exception ,It is because u are
            // enabling the visulizer to capture data & and after that setting
            // the capture size of buffer. U can't make any changes after
            // enabling it. I tried this same code and it's working fine for me
            visual = new Visualizer(mediaPlayer.getAudioSessionId());

            visual.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
            visual.setEnabled(true);
        } 
        catch (Exception ex) {
            Log.e("Visual Ex", ex.getMessage());
        }

    }

}

请参阅此链接以获得最佳示例https://github.com/felixpalmer/android-visualizer

U cant make any changes to object of visulizer after enabling to it. So just interchange to lines as shown in the belove code.

public class MediaPlayerActivity extends Activity {

    Visualizer visual;
    int formattedVizData[];
    byte rawWaveForm[];
    int cont = 0xFF;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Start media player & visualizer.
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
        mediaPlayer.start();

        // Create the Visualizer object and attach it to our media player.
        try {

            // this line is not actually causing Exception ,It is because u are
            // enabling the visulizer to capture data & and after that setting
            // the capture size of buffer. U can't make any changes after
            // enabling it. I tried this same code and it's working fine for me
            visual = new Visualizer(mediaPlayer.getAudioSessionId());

            visual.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
            visual.setEnabled(true);
        } 
        catch (Exception ex) {
            Log.e("Visual Ex", ex.getMessage());
        }

    }

}

Refere to this link for best example https://github.com/felixpalmer/android-visualizer

晒暮凉 2024-12-29 06:43:09

完成所有操作后,如果可视化未启动,请尝试 Visualizationview.startRendering()

after doing all if visualization doesnt start then try visualizationview.startRendering()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文