Streaming AAC audio with Android

后端 未结 5 899
遇见更好的自我
遇见更好的自我 2020-12-23 15:05

As I understand it, Android will only play AAC format audio if it\'s encoded as MPEG-4 or 3GPP.

I\'m able to play AAC audio encoded as M4A when it\'s local to the ap

5条回答
  •  再見小時候
    2020-12-23 15:33

    This work-around allows you to play M4A files from the net (and AAC files in other containers such as MP4 & 3GP). It simply downloads the file and plays from the cache.

    private File mediaFile;
    
    private void playAudio(String mediaUrl) {
        try {
            URLConnection cn = new URL(mediaUrl).openConnection();
            InputStream is = cn.getInputStream();
    
            // create file to store audio
            mediaFile = new File(this.getCacheDir(),"mediafile");
            FileOutputStream fos = new FileOutputStream(mediaFile);   
            byte buf[] = new byte[16 * 1024];
            Log.i("FileOutputStream", "Download");
    
            // write to file until complete
            do {
                int numread = is.read(buf);   
                if (numread <= 0)  
                    break;
                fos.write(buf, 0, numread);
            } while (true);
            fos.flush();
            fos.close();
            Log.i("FileOutputStream", "Saved");
            MediaPlayer mp = new MediaPlayer();
    
            // create listener to tidy up after playback complete
            MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    // free up media player
                    mp.release();
                    Log.i("MediaPlayer.OnCompletionListener", "MediaPlayer Released");
                }
            };
            mp.setOnCompletionListener(listener);
    
            FileInputStream fis = new FileInputStream(mediaFile);
            // set mediaplayer data source to file descriptor of input stream
            mp.setDataSource(fis.getFD());
            mp.prepare();
            Log.i("MediaPlayer", "Start Player");
            mp.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题