Skip to content

Instantly share code, notes, and snippets.

@vikaskore
Last active November 27, 2021 06:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikaskore/b8e68cb324da31121c8bc6a061e51612 to your computer and use it in GitHub Desktop.
Save vikaskore/b8e68cb324da31121c8bc6a061e51612 to your computer and use it in GitHub Desktop.
Play audio url in iOS Swift
//
// PlayAudio.swift
// Samples
//
// Created by VikasK on 22/04/19.
// Copyright © 2019 Vikaskore Software. All rights reserved.
//
import UIKit
import AVFoundation
class PlayAudio: UIViewController, AVAudioPlayerDelegate {
var audioPlayer:AVAudioPlayer!
@objc func playAudioButtonTapped(_ sender: UIButton) {
if sender.currentBackgroundImage == #imageLiteral(resourceName: "playAudio") { //Play
sender.setBackgroundImage(#imageLiteral(resourceName: "pause"), for: .normal) // set stop image
let url = URL(string: urlstring!)
downloadFileFromURL(url: url!)
} else {//stop
sender.setBackgroundImage(#imageLiteral(resourceName: "playAudio"), for: .normal) // set play image
audioPlayer.stop()
}
}
func downloadFileFromURL(url: URL){
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url) { (url, response, error) in
self.play(url: url!)
}
downloadTask.resume()
}
func play(url:URL) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: url as URL)
audioPlayer.prepareToPlay()
audioPlayer.volume = 2.0
audioPlayer.play()
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment