web-dev-qa-db-fra.com

Comment jouer un son sur iOS 11 avec Swift 4? Et où je place le fichier mp3?

J’ai vu beaucoup de tutoriels mais quand je clique sur le bouton (qui active le son func), le son ne joue pas J'ai vu le code recommandé par stackoverflow mais rien. J'ai mis l'info de fichier mp3 asset.xcasset. C'est juste?

3
Angelo Volpe

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)
    }
}
8
Arpit Jain

Swift 4.2/XCODE 10.1

Notez que vous devez appeler AVAudioSession.sharedInstance().setCategory() avec le paramètre mode dans Swift 4.2.

import AVFoundation

var audioPlayer: AVAudioPlayer?

func playSound() {
    if let audioPlayer = audioPlayer, audioPlayer.isPlaying { audioPlayer.stop() }

    guard let soundURL = Bundle.main.url(forResource: "audio_file", withExtension: "wav") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default)
        try AVAudioSession.sharedInstance().setActive(true)
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        audioPlayer?.play()
    } catch let error {
        Print.detailed(error.localizedDescription)
    }
}
4
Robert Nelson

Une solution très simple.

import AVFoundation

var myAudioPlayer = AVAudioPlayer?

func playAudioFile() {

    let audioFileURL = Bundle.main.url(forResource: "<name-of-file>", withExtension: "mp3/wav/m4a etc.")

    do {
        try myAudioPlayer = AVAudioPlayer(contentsOf: audioFileURL!)
    } catch let error {
        print(error.localizedDescription)
    }

    myAudioPlayer?.play()

}

Maintenant, jouez ce fichier audio n'importe où en appelant: playAudioFile()

2
amritpandey

Ajoutez votre fichier .mp3 à Bundle

import AVFoundation

let url = Bundle.main.url(forResource: "SampleAudio", withExtension: "mp3")

    let playerItem = AVPlayerItem(url: url!)
    let player=AVPlayer(playerItem: playerItem)
    let playerLayer=AVPlayerLayer(player: player)

    playerLayer.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
    self.view.layer.addSublayer(playerLayer)
    player.play()
1
Suresh Vutukuru

Vous pouvez également mettre une minuterie pour montrer la progression de la musique jouée

import AVFoundation

class ViewController: UIViewController {
var player : AVAudioPlayer?
var timer : Timer?
@IBOutlet var pauseBtn: UIButton!
@IBOutlet var replayBtn: UIButton!
@IBAction func rewind2(_ sender: Any) {

}
@IBAction func forward(_ sender: Any) {
    var time : TimeInterval = (player?.currentTime)!
    time += 5.0
    if (time > (player?.duration)!)
    {
        // stop, track skip or whatever you want
    }
    else
    {
        player?.currentTime = time
    }
}
@IBOutlet var progress: UIProgressView!
@IBAction func playClicked(_ sender: Any) {
    if player == nil {
        let resource = Bundle.main.url(forResource: "audioFX", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: resource!)
            player?.isMeteringEnabled = true
            player?.prepareToPlay()
        } catch let error {
            print(error)

        }
    }
    if player != nil {
        player?.play()
        enableTimer()
        player!.delegate = self as? AVAudioPlayerDelegate
    }
}
@IBAction func pauseClicked(_ sender: Any) {
    if(player != nil){
        if(player?.isPlaying == true){
            endTimer()
            player!.pause()
            pauseBtn.setTitle("Resume", for: .normal)
        }else{
            player!.play()
            enableTimer()
            pauseBtn.setTitle("Stop", for: .normal)
        }

    }
}
@IBAction func replayClicked(_ sender: Any) {
    if player != nil{
        endTimer()
        player = nil
        pauseBtn.setTitle("Stop", for: .normal)
        playClicked(replayBtn)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func enableTimer(){
    if(player != nil){
        timer = Timer(timeInterval: 0.1, target: self, selector: (#selector(self.updateProgress)), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: RunLoopMode(rawValue: "NSDefaultRunLoopMode"))
    }
}
func endTimer(){
    if(timer != nil){
        timer!.invalidate()
    }
}

@objc func updateProgress(){
    if(player != nil){
        player!.updateMeters() //refresh state
        progress.progress = Float(player!.currentTime/player!.duration)
    }
}

}

0
pravasi steffi

Manière simple avec Swift 4.2 :

import AVFoundation

et 

   let soundEffect = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
   var audioPlayer = AVAudioPlayer()

   @IBAction func buttonClick(sender: AnyObject) {
       do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundEffect)
            audioPlayer.play()
       } catch {
          // couldn't load file :(
       } 
   }
0
Sunil Targe