Getting error code without crashes after playing sound in Swift 5 - ios

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!

Related

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.

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

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

How do I assign value of type 'AVAudioPlayer.Type' to type 'AVAudioPlayer?'

I am making a sound effects application, and I am currently trying to get the sounds to play at the push of a button, but I cannot build it out until I can fix the errors. This is an error that I came across, but I don't know how to fix it.
This is my code:
class ViewController: UIViewController {
let noiseMaker = NoiseMaker()
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
#IBAction func curse(_ sender: AnyObject) {
noiseMaker.play(sender.tag)
if let url = Bundle.main.url(forResource: getName(tag: sender.tag), withExtension: "wav"){
player = try! AVAudioPlayer
The error it gave me was this:
Cannot assign value of type 'AVAudioPlayer.Type' to type 'AVAudioPlayer?'
Use like this:
player = try AVAudioPlayer(contentsOfURL: url)
player.delegate = self
player.prepareToPlay()
player.play()

Play sound effect without latency

I am trying to make a little app to teach myself some swift and I'm having some problems figuring out how to get my app to function a certain way.
My app should be able to play an airhorn sound just like the way it sounds in this video...
https://www.youtube.com/watch?v=Ks5bzvT-D6I
But each time I tap the screen repeatedly there is a slight delay before the sound is played so it's not sounding like that at all.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: hornSound, error: &error)
audioPlayer.prepareToPlay()
}
#IBAction func playSound(sender: UIButton) {
audioPlayer.pause()
audioPlayer.currentTime = 0
audioPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have also come across this thread about using spritekit
Creating and playing a sound in swift
And in trying that I got it to play the sound without the delay, but with sprite kit I can't stop the existing sound, so they just overlap which is not the effect I want.
Is there a work around to get this working the way it sounds in the video.
Apple recommends AVAudioPlayer for playback of audio data unless you require very low I/O latency.
So you might want to try another approach.
In one of my apps I play countdown sounds by creating a system sound ID from my wav file. Try this in your class:
import UIKit
import AudioToolbox
class ViewController: UIViewController {
var sound: SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)
AudioServicesCreateSystemSoundID(hornSound!, &self.sound)
}
#IBAction func playSound(sender: UIButton) {
AudioServicesPlaySystemSound(self.sound)
}
...
}

ReEdited : Audio not playing in real ios Device but playing in simulated devices in Swift2

This is my code in swift2 , absolutely no error ,Im running on a real device but no sound is coming ? no exceptions nothing am I missing something?
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBAction func play() {
audioPlayer.play()
}
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("drum", ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.volume = 1.0
audioPlayer.play()
print("yes")
}catch _ {
audioPlayer = nil
}
}
}
I found out what was the problem from one of the videos of Apple's WWDC Conference
http://adcdownload.apple.com/videos/wwdc_2010__hd/session_412__audio_development_for_iphone_os_part_1.mov (only viewable on safari)
The problem was audio routing , when i plugged in the earphone I could listen to the sound from the real device .
When the route is changed we need to set the proper audio routing using AVAudioSession . More info in that video above.
Import AVFoundation and add this to your viewDidLoad:
var err = NSErrorPointer()
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: err)

Resources