Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

play sound swift stack overflow

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)            
        try AVAudioSession.sharedInstance().setActive(true)

        /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        /* iOS 10 and earlier require the following line:
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */

        guard let player = player else { return }

        player.play()

    } catch let error {
        print(error.localizedDescription)
    }
}
Comment

PREVIOUS NEXT
Code Example
Swift :: access dictionary with index swift 
Swift :: unrecognized font family Helvetica-Regular 
Swift :: swift animate a label ishidden 
Swift :: swift quit app 
Swift :: this love taylor swift 
Swift :: swiftui slider 
Swift :: get request swift 
Swift :: swift uiswitch change size 
Swift :: swiftui pintch to zoom 
Swift :: round up swift 
Swift :: Return multiple value of different data types swift 
Swift :: how to check object is nil in swift 
Swift :: hide bottom tab bar swift 
Swift :: alert swiftui 
Swift :: swift reload tableview 
Swift :: swift enum 
Swift :: set button programmatically swift 
Swift :: swift push view controller programmatically 
Swift :: changing color of background swift 
Swift :: swift simulatore condition 
Swift :: map swift 
Swift :: how to merge 2 arrays in swift 
Swift :: UIFont.init bold 
Swift :: === in swift 
Swift :: while loop in swift 
Swift :: two integer value sum in swift 
Swift :: send receive udp swift 
Swift :: Swift enum With Associated Values 
Swift :: swift conditional statements 
Swift :: swift ranges 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =