blue
blue

Reputation: 7375

Swift- audio implementation crash: "EXC_BAD_INSTRUCTION"

I am trying to put audio into my app and I put in the following code and placed my mp3 audio file in my assets folder, and it crashed with: "EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)"

I could really use some help on what I'm doing wrong/ where I need to put the audio file. My code:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var audioPlayer = AVAudioPlayer()

        override func viewDidLoad() {
        super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    ScrollView.scrollEnabled = true
    ScrollView.contentSize = CGSize(width:473, height: 112)
    changer = 0
    tapView.hidden = true
    yoohooView.hidden = true
    var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Untitled", ofType: "mp3")!) //Crashes here
        println(alertSound)

        // Removed deprecated use of AVAudioSessionDelegate protocol
        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()

}

Upvotes: 3

Views: 446

Answers (1)

iHardikTrivedi
iHardikTrivedi

Reputation: 559

class ViewController: UIViewController {

var audioPlayer = AVAudioPlayer()

@IBOutlet weak var svScrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    svScrollView.scrollEnabled = true
    svScrollView.contentSize = CGSize(width:473, height: 112)
    var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("myMusic", ofType: "mp3")!)
    println(alertSound)
    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 tried above code. . . and it's fine to work for me . . . Please try this . . .

Upvotes: 1

Related Questions