【问题标题】:Convert mp3 into byte array and display byte array as image将mp3转换为字节数组并将字节数组显示为图像
【发布时间】:2018-08-04 13:08:33
【问题描述】:

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

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 的格式是否正确,你可以看到它只是 raw 文件夹中的一个资源文件。在日志输出中,我得到以下 I/worked:[B@d5fccc.我是 android studio 的新手(做一个大学项目)。我很确定字节数组不正确,但我不知道为什么。此外,当我尝试将其转换为图像并显示它时,它只是在图像视图中不显示任何内容。我正在尝试将图像显示为一种 WAV 图。 Expected Image

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

【问题讨论】:

  • 它不会;仅通过将字节设置为图像来显示 wav 图形。搜索how to get a wave form in Android
  • 谢谢你,看看:)

标签: java android arrays android-studio mp3


【解决方案1】:

MP3 文件是音频文件。它不是图像文件。 BitmapFactory 无法从 MP3 文件生成波形图。 BitmapFactory 可以解码位图(PNG、JPEG、WebP),仅此而已。

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

【讨论】:

  • 非常感谢,我会看看。只是为了兴趣,我将 MP3 转换为字节数组的方式正确吗?
  • @NicholasMott:好吧,因为BitmapFactorydecodeResource()decodeStream() 方法,所以没有必要将MP3 文件读入byte[](除了浪费堆空间之外)。通常我看到int i = 0; 而不是int i = Integer.MAX_VALUE;。否则,你那里应该没问题,虽然我现在睡眠不足,所以我可能会错过一些东西。
  • 不用担心,非常感谢,只是想尽可能多地学习:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 2015-08-16
  • 2013-05-19
  • 2014-04-14
  • 2011-11-25
相关资源
最近更新 更多