Yes I have looked around.
var congratzSound = NSBundle.mainBundle().URLForResource("Sweg.aiff", withExtension: "aiff")
var congratzPlayer:AVAudioPlayer? = AVAudioPlayer()
congratzPlayer = AVAudioPlayer(contentsOfURL: congratzSound, error: nil)
if let congratzPlayer = audioPlayer {
congratzPlayer.play()
}
This code complies fine, the file is in the Supporting Files section AND being coppied to the device.
What am I doing wrong? Is the file extension not playable? Is the congratzSound set up wrong?
Thanks in advance.
Using the following should solve your problem:
var congratzSound = NSBundle.mainBundle().URLForResource("Sweg", withExtension: "aiff")
If that doesn't work, try:
var congratzSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Sweg", ofType: "aiff")!)
Also, please check whether the file name is as-it-is (Sweg.aiff) in your code project and it is present in your app folder.
It is likely that your device is looking for Sweg.aiff.aiff while trying to play the sound, which obviously doesn't exist
Related
I have an app being used by people to receive orders with it needing to make a continuous sound until staff attend to it. It was working for two months then just started crashing a lot. For whatever reason, it runs fine on an iPad but not on iPhones running a recent operating system.
When this bit of code gets called it crashes:
guard let path = Bundle.main.path(forResource: "alert.mp3", ofType: nil) else { return }
let url = URL(fileURLWithPath: path)
do {
self.alertSoundEffect = try AVAudioPlayer(contentsOf: url)
} catch let err {
print("err: \(err)")
}
DispatchQueue.main.async {
self.alertSoundEffect.numberOfLoops = -1
self.alertSoundEffect.prepareToPlay()
self.alertSoundEffect.play()
}
The fix online to declare the alertSoundEffect variable like this:
private var alertSoundEffect : AVAudioPlayer!
has not worked at all.
I tried moving everything but the line:
self.alertSoundEffect.play()
to viewDidLoad as I thought maybe that code couldn't get called more than once, but it didn't help.
Specifically, the compiler highlights this line when it crashes:
self.alertSoundEffect = try AVAudioPlayer(contentsOf: url)
I tried using try AVAudioPlayer where it takes a Data object as a parameter or with including the type of audio file to be played, but that did not change anything.
When I try the AVAudioPlayer's delegate and declare it like this:
self.alertSoundEffect.delegate = self
right before the first lines of code I shared above Xcode highlights this line instead when it reliably crashes.
What else should I try?
I suppose your path is wrong.
Try this:
guard let path = Bundle.main.path(forResource: "alert", ofType: "mp3") else { return }
Also, if your audio file is short, like less than 30s, then try not to call self.alertSoundEffect.prepareToPlay(). Just call self.alertSoundEffect.play() right away.
Since iOS 13, this was causing a bug in my app, since I have notification sounds which are 3-10 seconds long.
If you initialise your AVAudioPlayer like var wrongMusicPlayer: AVAudioPlayer = AVAudioPlayer() OR wrongMusicPlayer = AVAudioPlayer() in any method then please remove it and just Declare like var wrongMusicPlayer: AVAudioPlayer!.
iOS 13.1 Crash in AVAudio Player
I'm creating a music app where different chimes will be played at different points in a rhythm cycle. So far, my code works fine in the Simulator but I'm not getting any sound on my device. I get sounds from other apps. Is there something wrong with my code? Thanks for you help!
import UIKit
import AudioToolbox
func playChime1() {
var chime1URL: NSURL?
var chime1ID:SystemSoundID = 0
let filePath = NSBundle.mainBundle().pathForResource("Chime", ofType: "mp3")
chime1URL = NSURL(fileURLWithPath: filePath!)
AudioServicesCreateSystemSoundID(chime1URL!, &chime1ID)
AudioServicesPlaySystemSound(chime1ID)
}
func playChime2() {
var chime2URL: NSURL?
var chime2ID:SystemSoundID = 0
let filePath = NSBundle.mainBundle().pathForResource("Chime2", ofType: "mp3")
chime2URL = NSURL(fileURLWithPath: filePath!)
AudioServicesCreateSystemSoundID(chime2URL!, &chime2ID)
AudioServicesPlaySystemSound(chime2ID)
}
func playChime3() {
var chime3URL: NSURL?
var chime3ID:SystemSoundID = 0
let filePath = NSBundle.mainBundle().pathForResource("Chime3", ofType: "mp3")
chime3URL = NSURL(fileURLWithPath: filePath!)
AudioServicesCreateSystemSoundID(chime3URL!, &chime3ID)
AudioServicesPlaySystemSound(chime3ID)
}
I had the same issue and realised my iPhone was on silent mode, taking it off silent played the sounds.
Unfortunately AudioToolbox sounds respond to the 'Ringer' volume of the device, and not the 'Volume' setting that audio through AVFoundation uses.
It makes sense, as AudioToolbox is supposed to be used for system sounds.
From related question: AudioServicesPlaySystemSound not working on iPad device
You can't play MP3 on iDevice, need to use a different framework.
My problem was the number of buffers allocated for AudioQueue, I allocated 3 and it worked on MacOS, however for iOS device you need at least 4
I am using an AVQueuePlayer to play local audio files which I have added to my Xcode project by dragging and dropping the .mp3 files into my folder in the project navigator pane. I then use this code to search thru my files and extract the files that I want, which I then use to fill a table view and to create AVPlayerItems for to play in my AVQueuePlayer.
My code works fine when I run the app on simulator but when i run the app on my iPhone, an error occurs and returns
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the code causing the issue...
var songNameArray: Array<String> = [String]()
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath("/Users/UsersName/Desktop/Xcode Projects Folder/LocalAudioFilePlayer/LocalAudioFilePlayer")!
while let element = enumerator.nextObject() as? String {
if element.hasSuffix("mp3") {
songNameArray.append(element)
print(element)
}
}
Are the files not being properly copied into the bundle which is then deployed to the iPhone? If so, what is the proper way to add the audio files?
I also tried this...
var songNameArray: Array<String> = [String]()
let path = String(NSBundle.mainBundle().resourcePath)
let songFiles = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
for item in songFiles {
if item.hasSuffix("mp3"){
songNameArray.append(item)
print("appended to songNameArray \(item)")
}
}
But I get the error
The folder “LocalAudioFilePlayer.app")” doesn’t exist
Any help is greatly appreciated
let path = String(NSBundle.mainBundle().resourcePath)
This line is not doing what you might think it does. NSBundle.mainBundle().resourcePath returns String?, which is an optional type. When you create a string from that by wrapping String() around it, it doesn't unwrap the optional, it creates a string describing the optional, which looks like this:
Optional("/Users/markbes/Library/Developer/CoreSimulator/Devices/18D62628-5F8A-4277-9045-C6DE740078CA/data/Containers/Bundle/Application/3DDC064C-0DD1-4BE9-8EA4-C151B65ED1E1/Resources.app")
What you want there is something more like
var path = NSBundle.mainBundle().resourcePath!
That unwraps the String? type, and gives you a string (or throws an error).
Did you select "Copy files if needed" then dragged mp3s into Project?
Try to load files as following:
let path = NSBundle.mainBundle().pathForResource("filename", ofType: "ext")
let url = NSURL.fileURLWithPath(path!)
var audioPlayer: AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Unable to load file")
}
Note: use only filename here, not the whole path.
It sounds like you haven't added your sound file to your target in the Xcode project. If they don't "belong" to a target, they won't get copied into the "resources" folder during building.
Select the sound files you want to use in the project navigator, and check the file inspector (view->Utilities->File Inspector, and make sure that the appropriate target is selected under "target membership".
edit: this is definitely not the problem in this case. Leaving this answer, as it may be useful for others running into a similar issue.
I'm trying to have a custom sound to be played when my application receives a notification, as part of the Apple Docs this should be done in the following way:
You can package the audio data in an aiff, wav, or caf file. Then, in Xcode, add the sound file to your project as a nonlocalized resource of the app bundle
My question is how do you create a nonlocalized resource? Is it automatically created when you drag/drop the audio file into the Xcode project? Is it specified in the Info.plist?
I'm able to play the sound file using the following code:
if let buttonBeep = self.setupAudioPlayerWithFile("0897", type:"aiff") {
self.buttonBeep = buttonBeep
}
buttonBeep?.volume = 1.0
buttonBeep?.play()
...
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("Player not available")
}
return audioPlayer
}
But no sound plays when a push notification is received.
When you drag the sound file into Xcode, make sure that you check the box to "Add To Targets".
What is the easiest library / framework to use?
I see lots of libraries but don't know which the industry standard is.
Here is some working Code for you to make it simpler. This works perfectly in my game.
import AVFoundation
var bgMusic:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("yourTune", withExtension: "mp3")!
bgMusic = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
bgMusic.numberOfLoops = 1
bgMusic.prepareToPlay()
bgMusic.play()
}
Make sure to change the name of your tune! :)
You don't need an additional library to play sounds in iOS. Just use what is provided to you by the corresponding SDK: AVAudioPlayer.