Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 Audio share with Whatsapp

I would like to share audio (.mp3) file via WhatsApp. I used UIActivityViewController but it just share mp3 files link not the file. How can i share the file to WhatsApp? There is my code:

 @IBAction func playTusu(_ sender: Any) {
    let url = URL(string: "https://freesound.org/data/previews/405/405511_2731495-lq.mp3")!
    let playerItem = CachingPlayerItem(url: url)

    playerItem.delegate = self

    player = AVPlayer(playerItem: playerItem)
    player.automaticallyWaitsToMinimizeStalling = false
    player.play()

}

@IBAction func paylas(_ sender: Any) {
    let url: [Any] = ["https://freesound.org/data/previews/405/405511_2731495-lq.mp3"]
    let avc = UIActivityViewController(activityItems: url, applicationActivities: nil)
    self.present(avc, animated: true)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

Thanks.

like image 910
melik ozbay Avatar asked Jan 18 '26 15:01

melik ozbay


1 Answers

In your paylas function you are trying to share a String but it should actually be a URL. The question has also been answered here: How do I share an Audio File in an App using Swift 3?

@IBAction func paylas(_ sender: Any) {
    let url: [Any] = [audioFileURL]
    let avc = UIActivityViewController(activityItems: url, applicationActivities: nil)
    self.present(avc, animated: true)
}

Update

The question says that you have a file but you only have the URL to the audio.

As @Leo Dabus mentioned in the comments, you have to download the audio and create a file first. Have a look at this SO question Download mp3 file. You also have to wait until the audio has downloaded. Then, you can share the file. Make sure to do that on the UI / Main Thread.

like image 130
Yannick Avatar answered Jan 20 '26 08:01

Yannick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!