• Android中怎样使用MediaPlayer播放byte数组音频文件


    场景

    在得到某音频文件的byte[]后使用MediaPlayer将其播放出来。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    新建工具类方法

            try {
                byte[] mp3SoundByteArray = Base64.decode(content, Base64.DEFAULT);// 将字符串转换为byte数组
                // create temp file that will hold byte array
                File tempMp3 = File.createTempFile("badao", ".mp3");
                tempMp3.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(tempMp3);
                fos.write(mp3SoundByteArray);
                fos.close();
    
                // Tried reusing instance of media player
                // but that resulted in system crashes...
                MediaPlayer mediaPlayer = new MediaPlayer();
    
                // Tried passing path directly, but kept getting
                // "Prepare failed.: status=0x1"
                // so using file descriptor instead
                FileInputStream fis = new FileInputStream(tempMp3);
                mediaPlayer.setDataSource(fis.getFD());
    
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException ex) {
                String s = ex.toString();
                ex.printStackTrace();
            }

    其中content是音频文件编码之后的字符串。

    然后将其解编码为字节数据,然后存储到临时文件并进行播放。

    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    input上传图片的坑
    nodejs创建一个静态文件服务器的根目录anywhere
    深浅拷贝
    es6中数组的flat()和flatMap()
    new Date()在ios上的坑
    一些常用的css Hack
    IntrospectorCleanupListener
    http header
    ActionContextCleanUp
    OpenSessionInViewFilter
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/14023058.html
Copyright © 2020-2023  润新知