将mp3转换为字节数组并将字节数组显示为图像

时间:2018-08-04 13:08:33

标签: java android arrays android-studio mp3

我正在尝试在Android Studio应用程序中获取mp3并将其转换为字节数组。然后,我尝试获取字节数组并将其转换为图像并在imageview中显示它。

public class ConvertMp3Activity extends AppCompatActivity {





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_convert_mp3);


}


public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[10240];
    int i = Integer.MAX_VALUE;
    while ((i = is.read(buff, 0, buff.length)) > 0) {
        baos.write(buff, 0, i);
    }


    return baos.toByteArray(); // be sure to close InputStream in calling function

}

public void selectMp3(View view) throws IOException
{

    MediaPlayer ring = MediaPlayer.create(ConvertMp3Activity.this,R.raw.testsong);
    ring.start();

    InputStream inStream = getApplicationContext().getResources().openRawResource(R.raw.testsong);

    byte[] music = new byte[inStream.available()];

        music = convertStreamToByteArray(inStream);
        Log.i("worked", music.toString());



    Bitmap bmp = BitmapFactory.decodeByteArray(music, 0, music.length);
    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    imageView.setImageBitmap(bmp);

    inStream.close();





}

上面的媒体播放器只是检查mp3格式是否正确,如您所见,它只是原始文件夹中的资源文件。在日志输出中,我得到以下I /工作结果:[B @ d5fccc。我是android studio的新手(正在做一个大学项目)。我很确定字节数组不正确,但是我无法弄清原因。另外,当我尝试将其转换为图像并显示时,它在图像视图中什么也没有显示。我正在尝试将图像显示为一种WAV图形。 Expected Image

任何帮助将不胜感激。我还允许读取清单中的外部存储的权限。

1 个答案:

答案 0 :(得分:0)

MP3文件是音频文件。它不是图像文件。 BitmapFactory无法从MP3文件生成波形图。 BitmapFactory只能解码位图(PNG,JPEG,WebP)。

有多个音频可视化程序库,例如thisthisthis。也许您可以调整其中一种以满足您的需求。