简体   繁体   中英

AVAudioPlayer is not playing any sound

I have made a class which handles audio that is played in my app:

import AVFoundation    

class GSAudio{
    var soundFileNameURL: NSURL = NSURL()
    var soundFileName = ""
    var soundPlay = AVAudioPlayer()

    func playSound (soundFile: String){

        soundFileName = soundFile
        soundFileNameURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundFileName, ofType: "aif", inDirectory:"Sounds")!)
        do{
            try soundPlay = AVAudioPlayer(contentsOfURL: soundFileNameURL)
        } catch {
            print("Could not play sound file!")
        }

        soundPlay.prepareToPlay()
        soundPlay.play()
    }
}

But the problem is when I call this code by using something like GSAudio().playSound("Start") from a different class, the sound does not play. Does anyone know why this is? Any help is appreciated.

Many thanks.

I have method AVAudioPlayer and its working fine when the button click action then perform this below method play well, but You want to call class and method (ex 'GSAudio().playSound("Start")') from different class, you create the delegate method to call, its work well.

@IBAction func btnPlayAction(sender: AnyObject) {

                let fileURL: NSURL = NSURL(string: previewUrl)!
                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()
}

hope its helpful

Check Your Sound File (URL) Path..(print That) and Checkout file:// Is There Or Not That's Main Problem In Your Sound ULR Ok Add it File://

//Or Use this One

NSURL *SoundURL = [NSURL fileURLWithPath:YourFilePath];

Try This One And Let me Know is i'm Correct or not

I have a helper on GitHub that does what you want. It's properly better to make this class a Singleton so you can control your music better and don't create multiple instances of your helper.

https://github.com/crashoverride777/Swift-Music-Helper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM