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是音頻文件編碼之后的字符串。

然后將其解編碼為字節數據,然后存儲到臨時文件並進行播放。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM