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

如何使用Flutter audioplayers播放Google Drive中的音频文件?

Flutter中Google Drive音频流式播放问题解决

问题根因

你用的/preview是Google Drive的网页预览地址,并非直接的音频资源链接。浏览器能正常播放是因为携带了你的Google账号认证Cookie,但Flutter的audioplayers底层依赖的MediaPlayer没有这些认证信息,所以请求返回401未授权错误。

快速解决方案:改用直接下载链接

把预览链接替换成Google Drive的直接下载格式:
原链接:https://drive.google.com/file/d/$id/preview
替换为:https://drive.google.com/uc?export=download&id=$id

修改后的代码:

import 'package:audioplayers/audioplayers.dart';
late AudioPlayer _player;
final directAudioUrl = 'https://drive.google.com/uc?export=download&id=$id';
await _player.play(UrlSource(directAudioUrl, mimeType: 'audio/mp4'));

关键注意点

  • 必须确保你的Google Drive文件设置为公开可查看,否则即使换了链接,还是会因权限不足无法访问。
  • 若音频文件体积过大,Google Drive可能会弹出确认下载页面,这种情况需额外处理跳转,但普通音频文件一般不会触发。

私有文件处理方案:用Google Drive API生成授权链接

如果不想把文件设为公开,可通过Google Drive API生成临时授权访问链接:

  1. 启用Google Drive API并获取服务账号密钥
  2. 调用API的files.get接口,指定alt=media参数获取资源流链接
  3. 将生成的临时授权链接传入audioplayers播放

示例代码逻辑:

// 先通过API获取授权后的临时播放链接
String authorizedUrl = await fetchAuthorizedDriveLink(fileId);
await _player.play(UrlSource(authorizedUrl, mimeType: 'audio/mp4'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:33:17