Exoplayer如何从字节数组播放音频-ByteArrayDataSource

5

使用Exoplayer,我正在尝试从字节数组播放音频文件。我正在尝试使用ByteArrayDataSource,但在调用构造函数时出现错误:new ByteArrayDataSource(data);以下是我想到的代码:

private void prepareExoPlayerFromByteArray(byte[] data){
        exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector(null), new DefaultLoadControl());
        exoPlayer.addListener(eventListener);


        final ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(data);

        /*
        DataSpec dataSpec = new DataSpec(byteArrayDataSource.getUri());
        try {
            byteArrayDataSource.open(dataSpec);
        } catch (IOException e) {
            e.printStackTrace();
        }
        */

        DataSource.Factory factory = new DataSource.Factory() {
            @Override
            public DataSource createDataSource() {
                return byteArrayDataSource;
            }
        };

        MediaSource audioSource = new ExtractorMediaSource(byteArrayDataSource.getUri(),
                factory, new DefaultExtractorsFactory(),null,null);
        exoPlayer.prepare(audioSource);
    }

我收到的错误信息如下:

E/ExoPlayerImplInternal: Internal runtime error.
                                                                                java.lang.NullPointerException
                                                                                    at com.google.android.exoplayer2.util.Assertions.checkNotNull(Assertions.java:107)
                                                                                    at com.google.android.exoplayer2.source.ExtractorMediaPeriod$ExtractingLoadable.<init>(ExtractorMediaPeriod.java:591)
                                                                                    at com.google.android.exoplayer2.source.ExtractorMediaPeriod.startLoading(ExtractorMediaPeriod.java:452)
                                                                                    at com.google.android.exoplayer2.source.ExtractorMediaPeriod.prepare(ExtractorMediaPeriod.java:165)
                                                                                    at com.google.android.exoplayer2.ExoPlayerImplInternal.maybeUpdateLoadingPeriod(ExoPlayerImplInternal.java:1260)
                                                                                    at com.google.android.exoplayer2.ExoPlayerImplInternal.updatePeriods(ExoPlayerImplInternal.java:1102)
                                                                                    at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:447)
                                                                                    at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:300)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                    at android.os.Looper.loop(Looper.java:234)
                                                                                    at android.os.HandlerThread.run(HandlerThread.java:61)
                                                                                    at com.google.android.exoplayer2.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)

错误似乎来自于ByteArrayDataSource的构造函数,它说传递给它的数据为null,但在调用它之前我已经检查过了,那个数组中有14002427字节。

/**
   * @param data The data to be read.
   */
  public ByteArrayDataSource(byte[] data) {
    Assertions.checkNotNull(data);
    Assertions.checkArgument(data.length > 0);
    this.data = data;
  } 

我做错了什么,怎样才能避免?有没有人有一个播放音频文件的Exoplayer工作示例,可以通过传递字节数组作为源来实现?

即使我使用了MediaPlayer,你建议的方法也不接受字节数组。虽然这与本题无关,因为我需要使用Exoplayer来完成此任务。 - ak93
有什么解决办法吗?我遇到了完全相同的问题。 - Chandru
请参考我的回答,如果可以的话,请给我点赞。谢谢 :) - RaghavPai
2个回答

7
class UriByteDataHelper {


        public Uri getUri(byte[] data) {

            try {
                URL url = new URL(null, "bytes:///" + "audio", new BytesHandler(data));
                return Uri.parse( url.toURI().toString());
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

        }

        class BytesHandler extends URLStreamHandler {
            byte[] mData;
            public BytesHandler(byte[] data) {
                mData = data;
            }

            @Override
            protected URLConnection openConnection(URL u) throws IOException {
                return new ByteUrlConnection(u, mData);
            }
        }

        class ByteUrlConnection extends URLConnection {
            byte[] mData;
            public ByteUrlConnection(URL url, byte[] data) {
                super(url);
                mData = data;
            }

            @Override
            public void connect() throws IOException {
            }

            @Override
            public InputStream getInputStream() throws IOException {

                return new ByteArrayInputStream(mData);
            }
        }
    }



  private void prepareExoPlayerFromByteArray(byte[] data){
        exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector(null), new DefaultLoadControl());
        exoPlayer.addListener(eventListener);

        final MByteArrayDataSource byteArrayDataSource = new MByteArrayDataSource(data);
        Log.i(TAG,"ByteArrayDataSource constructed.");
        Uri audioByteUri = new UriByteDataHelper().getUri(data);
        DataSpec dataSpec = new DataSpec(audioByteUri);
        try {
            byteArrayDataSource.open(dataSpec);
        } catch (IOException e) {
            e.printStackTrace();
        }


        DataSource.Factory factory = new DataSource.Factory() {
            @Override
            public DataSource createDataSource() {
                return byteArrayDataSource;
            }
        };
        Log.i(TAG,"DataSource.Factory constructed.");


        MediaSource audioSource = new ExtractorMediaSource(audioByteUri,
                factory, new DefaultExtractorsFactory(),null,null);
        Log.i(TAG,"Audio source constructed.");
        exoPlayer.prepare(audioSource);
        initMediaControls();
    }

您已创建了一个新的MByteArrayDataSource类型对象。这与标准的com.google.android.exoplayer2.upstream.ByteArrayDataSource有什么不同吗? - ciaranodc
如果没有音频文件,只有字节数组,有没有办法让这个工作?因为数据是通过NDN传输的,所以我没有可用的Uri。 - ciaranodc
Uri audioByteUri = new UriByteDataHelper().getUri(data);这里的data是字节数组。 - RaghavPai
"bytes:///" + "audio" 是最终的,您不需要更改。 - RaghavPai
我不得不将MByteArrayDataSource更改为ByteArrayDataSource,现在它完美地工作了。 - MrinmoyMk
显示剩余8条评论

0
byteArrayDataSource.getUri()将会是null,如果你不调用byteArrayDataSource.open(DataSpec dataSpec)。请看代码;
public final class ByteArrayDataSource implements DataSource {

  private final byte[] data;

  private Uri uri;
  private int readPosition;
  private int bytesRemaining;

  /**
   * @param data The data to be read.
   */
  public ByteArrayDataSource(byte[] data) {
    Assertions.checkNotNull(data);
    Assertions.checkArgument(data.length > 0);
    this.data = data;
  }

  @Override
  public long open(DataSpec dataSpec) throws IOException {
    uri = dataSpec.uri;
    readPosition = (int) dataSpec.position;
    bytesRemaining = (int) ((dataSpec.length == C.LENGTH_UNSET)
        ? (data.length - dataSpec.position) : dataSpec.length);
    if (bytesRemaining <= 0 || readPosition + bytesRemaining > data.length) {
      throw new IOException("Unsatisfiable range: [" + readPosition + ", " + dataSpec.length
          + "], length: " + data.length);
    }
    return bytesRemaining;
  }

  @Override
  public int read(byte[] buffer, int offset, int readLength) throws IOException {
    if (readLength == 0) {
      return 0;
    } else if (bytesRemaining == 0) {
      return C.RESULT_END_OF_INPUT;
    }

    readLength = Math.min(readLength, bytesRemaining);
    System.arraycopy(data, readPosition, buffer, offset, readLength);
    readPosition += readLength;
    bytesRemaining -= readLength;
    return readLength;
  }

  @Override
  public Uri getUri() {
    return uri;
  }

  @Override
  public void close() throws IOException {
    uri = null;
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接