简体   繁体   中英

AVAudioPlayer not playing mp3 file

I have run this app on my simulator as well as my phone and with multiple mp3 files however I cannot get sound to output from the app. I have included the mp3 file in the supported files. I am honestly lost as to what to do next. I receive no errors however there is no audio.

@IBAction func play (sender: AnyObject){

func sharedInstance() {
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var audioPlayer = AVAudioPlayer()
        var song = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pingpong", ofType: "mp3")!)
        println(song)



        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
}
sharedInstance()

}

Just make your var audioPlayer = AVAudioPlayer() global for your class like shown in below code:

And I have modified your code to make it safe:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    @IBAction func play (sender: AnyObject){

        var categoryError: NSError?
        if AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) {
            println("AVAudioSession Category Playback OK")
            var activateError: NSError?
            if AVAudioSession.sharedInstance().setActive(true, error: &activateError) {
                println("AVAudioSession is Active")
                var song = NSBundle.mainBundle().URLForResource("we_cant_Stop", withExtension: "mp3")!
                var error:NSError?
                audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
                audioPlayer.play()

            } else if let activateError = activateError {
                println(activateError.description)
            }
        } else if let categoryError = categoryError {
            println(categoryError.description)
        }
    }
}

This is working fine.

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