Playing an MP3 file

This entry is part 33 of 33 in the series iOS Apps

This is part of the code that I have used in my App to play MP3 audio file.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func playAudio(_ sender: AnyObject) {
        
      let urlstring = "https://firebasestorage.googleapis.com/v0/b/learnchinese-e140b.appspot.com/o/Chinese_Sound%2F3persons.mp3?alt=media&token=128d4b79-d7cd-46a6-9ea0-22ee962492a2"
        
        let url = URL(string: urlstring)
        print("the url = \(url!)")
        downloadFileFromURL(url!)
        
    }
    
    func downloadFileFromURL(_ url:URL){
        
        var downloadTask:URLSessionDownloadTask
        
        downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) -> Void in
            
            self.play(url!)
            
        })
        
        downloadTask.resume()
        
    }
    
    func play(_ url:URL) {
        print("playing \(url)")
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }
    }

}

 

Shuffle array in a class

This entry is part 33 of 41 in the series Swift

import UIKit

class ArrayObject : NSObject {
    
    var numbers = [1,2,3,4,5]
    
    func shuffleNumbers() {
        numbers.shuffle()
    }
}

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }
        
        for (unshuffledCount, firstUnshuffled) in zip(stride(from: c, to: 1, by: -1), indices) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

let array = ArrayObject()

array.shuffleNumbers()

print(array.numbers[1])