Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?

Tags:

ios

audio

I saw a lot of tutorials but when i click button (that actvivate The func playsound) The sound doesn’t play. I saw the code reccomended by stackoverflow but nothing. I put The mp3 file info asset.xcasset. It’s right?

like image 406
Angelo Volpe Avatar asked Nov 28 '22 13:11

Angelo Volpe


1 Answers

SWIFT 4 / XCODE 9.1

import AVFoundation

var objPlayer: AVAudioPlayer?

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

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        // For iOS 11 
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        // For iOS versions < 11 
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) 

        guard let aPlayer = objPlayer else { return }
        aPlayer.play()

    } catch let error {
        print(error.localizedDescription)
    }
}
like image 73
Arpit Jain Avatar answered Dec 06 '22 20:12

Arpit Jain