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

前端 未结 6 724
一整个雨季
一整个雨季 2021-01-03 07:47

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

相关标签:
6条回答
  • 2021-01-03 08:18

    You can also put a timer to show the progress of the music played

    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 讨论(0)
  • 2021-01-03 08:20

    A very simple solution.

    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()
    
    }
    

    Now, play this audio file anywhere by calling: playAudioFile()

    0 讨论(0)
  • 2021-01-03 08:21

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-03 08:22

    Simple way with Swift 4.2:

    import AVFoundation
    

    and

       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 讨论(0)
  • 2021-01-03 08:29

    SWIFT 4.2 / XCODE 10.1

    Note that you must call AVAudioSession.sharedInstance().setCategory() with the mode parameter in 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)
        }
    }
    
    0 讨论(0)
  • 2021-01-03 08:31

    Add your .mp3 file to 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()
    
    0 讨论(0)
提交回复
热议问题