Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) - ios

I'm new in Swift. I am trying to Run this code but got an error:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) a.
Error appears here:
self.player.play()
Can anyone help in this issue?
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
if let audioPath = Bundle.main.path(forResource: "music", ofType: "mp3") {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath))
}
} catch {
print("ERROR")
}
self.player.play()
}

What you doing with your code is:
Creating an instance of AVAudioPlayer without any data
Trying to create a new instance with some data from music.mp3 file
Playing it
If the audioPath is not correct, then the player is not correctly created: application will use the one without valid data, leading to a crash during playback.
Your code can be written making the player optional, which helps preventing the crash:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
player = initializePlayer()
player?.play()
}
private func initializePlayer() -> AVAudioPlayer? {
guard let path = Bundle.main.path(forResource: "music", ofType: "mp3") else {
return nil
}
return try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
}
}
Some changes performed to the code:
player is now optional: there is no need to initialize it twice. Plus if the initialization goes well you can use it without problems, otherwise your app won't crash.
The play method is now in an optional chain
I've moved the initialization of the player in a separate private methods, to maintain the code readable. Feel free to change it, it is just a suggestion.

I've got it. The issue is that the file isn't being coping to my app bundle. To fix it:
Click your project
Click your target
Select Build Phases
Expand Copy Bundle Resources
Click '+' and select your file.
Thanks Denis Hennessy

Related

Getting error code without crashes after playing sound in Swift 5

I am very new to swift and programming so in this udemy project I decided to make it without looking to instruction video. So when I open up simulator everything works perfect but I get an error in console and as a perfectionist I want to get rid of it.
My Code Follows:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func keyPressed(_ sender: Any) {
let cSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "C", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: cSoundUrl as URL)
}catch{
print("Error was there for C!")
}
audioPlayer.play()
}
And the error follows as this;
2021-07-14 22:03:49.248871+0300 Xylophone[40027:5196447] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x60000214c320> F8BB1C28-BAE8-11D6-9C31-00039315CD46
As I said I am in a beginner state I don't even understand what does AddInstanceForFactory means.
Thanks for any help in advance!

Audio is not playing without breakpoint

The sound file is playing when i add breakpoints inside the below functions. But the sound file is not playing if i run the application without breakpoint.
I am calling this function in button click as Sound().playSounds()
import AVFoundation
class Sound {
private var audioplayer:AVAudioPlayer!
func playSounds()
{
if let path = Bundle.main.path(forResource: "Audio/ring.mp3", ofType: nil)
{
let url = URL(fileURLWithPath: path)
do {
self.audioplayer = try AVAudioPlayer(contentsOf: url)
self.audioplayer.numberOfLoops = 3
self.audioplayer.prepareToPlay()
self.audioplayer.play()
}
catch {
print("Couldn't load file")
}
}
}
}
Your Sound object gets deallocated before it has a chance to play a sound.
Store it where you are calling it from:
var sound = Sound()
// for example to play sound call
func playPressed(){
sound.playSounds()
}
Chane your player into a global variable like this. Otherwise it'll be a deadlock.
var audioplayer:AVAudioPlayer!
Also you may want to change your resource path extracting logic to below,
if let path = Bundle.main.path(forResource: "ring.mp3", ofType: "mp3")
Or you can directly use Bundle.main.url(forResource: withExtention) method.

Audio not playing after button is clicked

I was following this tutorial on YouTub: https://www.youtube.com/watch?v=qC6DzF_ACpQ&t=714s , and at 12.18 when he clicks the button, it plays audio. I followed all the exact same steps as he did in the video and it is not working for me.
I am pretty new to coding in swift so I did not try anything else other than restarting the whole project again, but it did not work.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func aTapped(_ sender: Any) {
let url = Bundle.main.url(forResource: "a", withExtension: "mp3")
// Make sure that weve got the url, otherwise abord
guard url != nil else{
return
}
do{
audioPlayer = try AVAudioPlayer(contentsOf: url!)
audioPlayer?.play()
}
catch{
print("error")
}
}
I just want the audio to play when I click the button assigned to the code, but when I click the button, no audio plays at all.
Please Help.

AVAudioPlayer returning nil after game has been running for a while

I'm current developing a small game where balloons float up from the bottom of the screen and the player has to pop them before they reach the top.
Each balloon object contains a method to safely set up it's AVAudioPlayer's:
func setUpAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
}catch {
print("BALLOON ERROR - AudioPlayer not avaliable.")
}
return audioPlayer
}
Then in each balloons init() method I run the following code:
if let popSound = self.setUpAudioPlayerWithFile("PopSound", type: "wav") {
self.popSound = popSound
}
Which works absolutely fine until a couple of minutes into the game. At this point I start receiving "BALLOON ERROR - AudioPlayer not available." in the console for every single balloon being spawned from then onwards indicating that my resource isn't being found?
At this time my SKEmitterNodes start to return nil as well. (2016-08-13 18:59:54.527 Stop & Pop[256:13785] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL)
Is there anything obvious I'm missing that could be causing these errors?
I hope I've provided enough information, thank you for reading.
No... this won't work. You have to instantiate the audioPlayer variable into the Class Level.
I tried to do this, instantiated the var audioPlayer on another ViewController at the Class Level.
Your best bet is to localize this method into your ViewController, and put the audioPlayer here:
class YourClassName : Type {
var audioPlayer : AVAudioPlayer?
yourMethodForCalling() {
}

Swift - AVAudioPlayer not playing sound

I have a sound called speeding.mp3 and I am trying to make a AVAudioPayer instance with it by doing this in the root of the class:
let speedingAudioPlayer = try! AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3")!)
Then when I run the app it throws an error but I don't know why this is happening. The speeding.mp3 file is in the Bundle Resources drop down in Build Phases so it should find it fine. If I try to print out the URL in the simulator and paste it into Safari it loads and plays the file like normal. I am importing AVFoundation into the class and the framework into the project.
Use this code snippet to debug your error,
if let URL = NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3") {
do {
let speedingAudioPlayer = try AVAudioPlayer(contentsOfURL: URL)
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("No such file exist")
}
I found another question where the var is placed outside the class because otherwise it would be deallocated by the phone.
AVAudioPlayer Object Sound Not Playing - Swift
import UIKit
import AVFoundation
class CustomAudioPlayer {
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playSound("sound_file_name")
}
func playSound(soundName: String)
{
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
}
Try this code for playing the sound.

Resources