AVAudioPlayer not playing audio in Swift

旧巷老猫 提交于 2019-11-29 02:04:56

There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:

var player : AVAudioPlayer! = nil // will be Optional, must supply initializer

@IBAction func playMyFile(sender: AnyObject?) {
    let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
    let fileURL = NSURL(fileURLWithPath: path)
    player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
    player.prepareToPlay()
    player.delegate = self
    player.play()
}

I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.

One final point, which may or may not be relevant: not every m4a file is playable. A highly compressed file, for example, can fail silently (pun intended).

Important that AvPlayer is class member and not in the given function, else it goes out of scope... :)

Here is a working snippet from my swift project. Replace "audiofile" by your file name.

    var audioPlayer = AVAudioPlayer()
    let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
    audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    audioPlayer.play()

You can download fully functional Swift Audio Player application source code from here https://github.com/bpolat/Music-Player

for some reason (probably a bug) Xcode can't play certain music files in the .m4a and the .mp3 format I would recommend changing them all to .wav files to get it to play

//top of your class
var audioPlayer = AVAudioPlayer

//where you want to play your sound
let Sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: Sound as URL)
        audioPlayer.prepareToPlay()
    } catch {
        print("Problem in getting File")
    }
    audioPlayer.play()

var audioPlayer = AVAudioPlayer()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("KiepRongBuon", ofType: "mp3")!)
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()

I used the below code in my app and it works. Hope that is helpful.

var audioPlayer: AVAudioPlayer!
if var filePath = NSBundle.mainBundle().pathForResource("audioFile", ofType:"mp3"){

     var filePathUrl = NSURL.fileURLWithPath(filePath)
     audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
     audioPlayer.play()
}else {
     println("Path for audio file not found")
}

Based on @matt answer but little bit detailed 'cause original answer did not completely satisfied me.

import AVFoundation

class YourController: UIViewController {

  private var player : AVAudioPlayer?

  override func viewDidLoad() {
     super.viewDidLoad()

     prepareAudioPlayer()
  }

  @IBAction func playAudio() {

      player?.play()
  }
}

extension YourController: AVAudioPlayerDelegate {}

private extension YourController {

    func prepareAudioPlayer() {

        guard let path = Bundle.main.path(forResource: "you-audio", ofType:"mp3") else {
            return
        }
        let fileURL = URL(fileURLWithPath: path)
        do {
            player = try AVAudioPlayer(contentsOf: fileURL)
        } catch let ex {
            print(ex.localizedDescription)
        }
        player?.prepareToPlay()
        player?.delegate = self
    }
}

In Swift Coding using Try catch, this issues will solve and play audio for me and my code below,

var playerVal = AVAudioPlayer()

         @IBAction func btnPlayAction(sender: AnyObject) {
                let fileURL: NSURL = NSURL(string: url)!
                    let soundData = NSData(contentsOfURL: fileURL)

                    do {
                        playerVal = try AVAudioPlayer(data: soundData!)
                    }
                    catch {
                        print("Something bad happened. Try catching specific errors to narrow things down",error)
                    }

                    playerVal.delegate = self
                    playerVal.prepareToPlay()

                    playerVal.play()

              }

swift 3.0:

 import UIKit
    import AVFoundation

    class ViewController: UIViewController
    {
        var audioplayer = AVAudioPlayer()

        @IBAction func Play(_ sender: Any)
        {
            audioplayer.play()
        }
        @IBAction func Pause(_ sender: Any)
        {
            if audioplayer.isPlaying
            {
                audioplayer.pause()
            }
            else
            {

            }
        }
        @IBAction func Restart(_ sender: Any)
        {
            if audioplayer.isPlaying
            {
                audioplayer.currentTime = 0
                audioplayer.play()
            }
            else
            {
                audioplayer.play()
            }

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

            do
            {
                audioplayer = try AVAudioPlayer(contentsOf:URL.init(fileURLWithPath:Bundle.main.path(forResource:"bahubali", ofType: "mp3")!))
                audioplayer.prepareToPlay()

                var audioSession = AVAudioSession.sharedInstance()

                do
                {
                    try audioSession.setCategory(AVAudioSessionCategoryPlayback)
                }

                catch
                {

                }
            }
            catch
            {
                print (error)
            }

        }
     }   
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!