You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用just-audio播放内嵌多段MP3的文件?参考Android MediaPlayer

使用just-audio播放内嵌多段MP3的指定片段

核心思路

just-audio在Android平台底层依赖ExoPlayer,我们可以通过构建指定文件偏移量和长度的自定义数据源,让just-audio精准播放内嵌的单个MP3片段,效果等价于Android MediaPlayer的setDataSource(FileDescriptor fd, long offset, long length)方法。

具体实现步骤

1. 获取文件描述符

先拿到内嵌MP3文件对应的FileDescriptor,示例如下:

// 从本地文件获取
val targetFile = File("/storage/emulated/0/your_embedded_mp3_file")
val fileDescriptor = FileInputStream(targetFile).fd

2. 构建自定义数据源工厂

创建返回指定片段数据源的工厂类,传入目标片段的偏移量和长度:

// 替换为目标片段的实际偏移量和contentLength
val segmentOffset = 12345L
val segmentLength = 67890L

val customDataSourceFactory = DataSource.Factory {
    FileDataSource().apply {
        open(
            FileDataSource.FileDataSourceDescriptor(
                fileDescriptor,
                segmentOffset,
                segmentLength
            )
        )
    }
}

3. 配置并播放

将自定义数据源传入just-audio的AudioPlayer,完成播放配置:

val audioPlayer = AudioPlayer()

// 构建适配just-audio的媒体源
val mediaSource = ProgressiveMediaSource.Factory(customDataSourceFactory)
    .createMediaSource(MediaItem.fromUri("file:///dev/null")) // 占位URI,实际使用自定义数据源

// 启动播放
audioPlayer.setMediaSource(mediaSource)
audioPlayer.prepare()
audioPlayer.play()

4. 切换片段播放

如需切换到其他MP3片段,重新构建数据源和媒体源即可:

fun switchToSegment(newOffset: Long, newLength: Long) {
    val newDataSourceFactory = DataSource.Factory {
        FileDataSource().apply {
            open(
                FileDataSource.FileDataSourceDescriptor(
                    fileDescriptor,
                    newOffset,
                    newLength
                )
            )
        }
    }
    val newMediaSource = ProgressiveMediaSource.Factory(newDataSourceFactory)
        .createMediaSource(MediaItem.fromUri("file:///dev/null"))
    
    audioPlayer.stop()
    audioPlayer.setMediaSource(newMediaSource)
    audioPlayer.prepare()
    audioPlayer.play()
}

注意事项

  • 播放期间需保持FileDescriptor处于打开状态,避免提前关闭导致播放中断
  • 偏移量和长度参数必须与MP3片段的实际位置、大小完全匹配,否则可能出现播放异常
  • 页面销毁时务必调用audioPlayer.release()释放播放器资源,避免内存泄漏

内容的提问来源于stack exchange,提问作者qcl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:47:12