简体   繁体   中英

How to play audio files from Google Drive (Swift 5)

In my project I use a Google Drive API. I get a list of the user's files and can save them to the device memory. I also want to be able to play audio files directly from Google Drive, but I just can't do it. The AVPlayer doesn't want to play the audio file using the URL link, which I transfer to him. But if I paste this link into any browser, then the track is played. Has anyone encountered this and knows how to fix the problem? I would be grateful for any help. My code looks like this (it's a simplified version):

import AVKit

class MyVC: UIViewController {
...
var player: AVPlayer!
...
private func playTrack() {
   let url = URL(string: "https://drive.google.com/uc?export=open&id=XXXXX" //where XXXXX is an item id
   let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
   player = AVPlayer(playerItem: playerItem)
   player!.play()
   }
}

For example URL link which I transfer to the AVPlayer looks like this:

https://drive.google.com/uc?export=open&id=1JzuAhQ-7R01wLhtD8zEN_sC5nvFlt7wU

But if I paste it into the browser it automatically changes and looks like this:

https://doc-0g-1s-docs.googleusercontent.com/docs/securesc/anu2dlv0j1ugsoh1pb6b8qpkkt7k1j6k/hp3dnmru336i1cpkk4f5p4bstc83b30f/1602827400000/02426681720429398713/02426681720429398713/1JzuAhQ-7R01wLhtD8zEN_sC5nvFlt7wU?e=open&authuser=0&nonce=4dd9dhoo6he8g&user=02426681720429398713&hash=o87f0k3t4iv19ugae899urmcjd14ogiq

Maybe it's important.

You files should be shared by a direct link in Google Drive to play it so you can make it manually or using API eg:

在此处输入图片说明

And then use direct links in format: https://drive.google.com/uc?export=open&id=XXXXX .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM