So I have a list of audio files and when a cell is pressed it plays the audio. This works fine but I am not able to pause it by clicking the same cell again.
My code for the table view:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let a = indexPath.section;
let b = indexPath.row;
var path = NSBundle.mainBundle().pathForResource(musicArray[b], ofType: "mp3")
var error:NSError?
do{
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!))
}
catch
{
print("Something bad happened")
}
if (audioPlayer.playing)
{
audioPlayer.pause();
}
else
{
audioPlayer.play();
}
}
musicArray has the titles of the audio files
You're creating a new AVAudioPlayer every time you select the cell. You need to keep a reference to the previous one and tell that audio player to pause.
You can create a singleton object.
import AVFoundation
class SomeAudioManager: NSObject, AVAudioPlayerDelegate
{
class var sharedInstance: SomeAudioManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: SomeAudioManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SomeAudioManager()
}
return Static.instance!
}
func audioView(songname: String,format: String) {
let audioPlayer: AVAudioPlayer
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(songname, ofType:format)!), fileTypeHint: AVFileTypeMPEGLayer3)
audioPlayer.delegate = self;
audioPlayer.play()
} catch {
// error
}
}
}
It will be alive through the whole app.
How to implement AVAudioPlayer Inside Singleton Method?
You can just create a singleton of the player so that you will always know if it's playing or not.
Playing a sound is so verbose in code and would like to create an extension of AVAudioSession if possible. The way I'm doing it is assigning an object to a variable, but need help/advise on how to set up this function so it's reusable and optimized.
Here's what I have:
func playSound(name: String, extension: String = "mp3") {
let sound = NSBundle.mainBundle().URLForResource(name, withExtension: extension)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
audioPlayer = try AVAudioPlayer(contentsOfURL: sound!)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
} catch { }
}
I think I have to create the audioPlayer variable outside of this function, otherwise I had a hard time playing anything. Maybe it can be self contained? I'm hoping to use it something like this:
AVAudioSession.sharedInstance().play("bebop")
Taking the code straight from your example I see two options:
1) Is there any particular reason why you want to make it as an extension of AVAudioSession? If not, just make your own service!
class AudioPlayerService {
static let sharedInstance = AudioPlayerService()
var audioPlayer: AVAudioPlayer?
func playSound(name: String, extension: String = "mp3") {
let sound = NSBundle.mainBundle().URLForResource(name, withExtension: extension)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
audioPlayer = try AVAudioPlayer(contentsOfURL: sound!)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
} catch { }
}
}
2) If you do need to make it as an extension of AVAudioSession, then take a look at associated objects
extension AVAudioSession {
private struct AssociatedKeys {
static var AudioPlayerTag = "AudioPlayerTag"
}
var audioPlayer: AVAudioPlayer? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.AudioPlayerTag) as? AVAudioPlayer
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.AudioPlayerTag,
newValue as AVAudioPlayer?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
func playSound(name: String, extension: String = "mp3") {
let sound = NSBundle.mainBundle().URLForResource(name, withExtension: extension)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
audioPlayer = try AVAudioPlayer(contentsOfURL: sound!)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
} catch { }
}
}
This is the best way I have found to add sound
Filename is shootMissile.wav
func shootMissileSound() {
if let soundURL = NSBundle.mainBundle().URLForResource("shootMissile", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}
}
I have two swift files - my ViewController:UIViewController and AudioPlayer:AVAudioPlayer.
My AudioPlayer file has this function
func seaGullSound() {
var tmp = AVAudioPlayer()
var seaGullSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Gulls", ofType: "mp3")!)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
tmp = AVAudioPlayer(contentsOfURL: seaGullSound, error: &error)
tmp.prepareToPlay()
tmp.play()
println("This function got called!")
}
I'm trying to call that function in my ViewController thru tapping a button, using this code:
#IBAction func playSound(sender: AnyObject) {
var audio = AudioPlayer()
audio.seaGullSound()
}
The sound is not played when I click the button. However, the print statement works. I can get the audio to play if I move seaGullSound() to the ViewController file, so I know the mp3 does work. I haven't moved the audio to ViewController because I want to develop the habit of not crowding all my code into one file. Thanks in advance for the help.
edit:
class HighScore: UIViewController {
var audioInitializer = AudioPlayer()
func updateHighScore(score:Int) -> String {
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
//Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
//call applause sound
audioInitializer.applauseSound()
//set score
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
//use below line to reset high score for testing
//NSUserDefaults.standardUserDefaults().removeObjectForKey("highscore")
return String(NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
}}
here is the file with the sounds:
class AudioPlayer: AVAudioPlayer {
var soundMaster = AVAudioPlayer()
func tappingSound() {
var tapSoundURL = NSBundle.mainBundle().URLForResource("tapSound", withExtension: "mp3")
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
soundMaster = AVAudioPlayer(contentsOfURL: tapSoundURL, error: &error)
soundMaster.prepareToPlay()
soundMaster.play()
}
//need to call in highscore.swift
func applauseSound() {
var tapSoundURL = NSBundle.mainBundle().URLForResource("applause", withExtension: "mp3")
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
soundMaster = AVAudioPlayer(contentsOfURL: tapSoundURL, error: &error)
soundMaster.prepareToPlay()
soundMaster.play()
println("did this get called?")
}}
You just have move the declaration of your tmp AVAudioPlayer out of your method. Declare it as class variable.
You should also use URLForResource instead of pathForResource:
let seaGullSoundURL = NSBundle.mainBundle().URLForResource("Gulls", withExtension: "mp3")!
Try like this:
import UIKit
import AVFoundation
class HighScore: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateHighScore(score:Int) -> String {
//Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
if score > NSUserDefaults().integerForKey("highscore") {
//call applause sound
playAudio("applause")
//set score
NSUserDefaults().setInteger(score, forKey: "highscore")
}
//use below line to reset high score for testing
//NSUserDefaults.standardUserDefaults().removeObjectForKey("highscore")
return NSUserDefaults().integerForKey("highscore").description
}
func playAudio(audioName: String ) {
var error:NSError?
if let audioURL = NSBundle.mainBundle().URLForResource(audioName, withExtension: "mp3") {
audioPlayer = AVAudioPlayer(contentsOfURL: audioURL, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
} else if let error = error {
println(error.description)
}
}
#IBAction func playSound(sender: UIButton) {
playAudio("Gulls")
}
}
I have this code in a very simple, single view Swift application in my ViewController:
var audioPlayer = AVAudioPlayer()
#IBAction func playMyFile(sender: AnyObject) {
let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
let url = NSURL(fileURLWithPath: fileString)
var error : NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
if (audioPlayer.isEqual(nil)) {
println("There was an error: (er)")
} else {
audioPlayer.play()
NSLog("working")
}
I have added import AVFoundation and audioPlayer is a global variable. When I execute the code, it does print "working", so it makes it through without errors but no sound is played. The device is not in silent.
There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:
var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
#IBAction func playMyFile(sender: AnyObject?) {
let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
}
I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.
One final point, which may or may not be relevant: not every m4a file is playable. A highly compressed file, for example, can fail silently (pun intended).
Important that AvPlayer is class member and not in the given function, else it goes out of scope... :)
I had to declare a global player variable
var player: AVAudioPlayer!
and set it in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
player = AVAudioPlayer()
}
Then I could play the audio file wherever like this:
func playAudioFile(){
do {
if audioFileUrl == nil{
return
}
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: audioFileUrl, fileTypeHint: AVFileType.m4a.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
print("PLAYING::::: \(audioFileUrl)")
}
catch let error {
print(error.localizedDescription)
}
}
}
Here is a working snippet from my swift project. Replace "audiofile" by your file name.
var audioPlayer = AVAudioPlayer()
let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
You can download fully functional Swift Audio Player application source code from here https://github.com/bpolat/Music-Player
for some reason (probably a bug) Xcode can't play certain music files in the .m4a and the .mp3 format I would recommend changing them all to .wav files to get it to play
//top of your class
var audioPlayer = AVAudioPlayer
//where you want to play your sound
let Sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: Sound as URL)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
audioPlayer.play()
var audioPlayer = AVAudioPlayer()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("KiepRongBuon", ofType: "mp3")!)
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 used the below code in my app and it works. Hope that is helpful.
var audioPlayer: AVAudioPlayer!
if var filePath = NSBundle.mainBundle().pathForResource("audioFile", ofType:"mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
audioPlayer.play()
}else {
println("Path for audio file not found")
}
In Swift Coding using Try catch, this issues will solve and play audio for me and my code below,
var playerVal = AVAudioPlayer()
#IBAction func btnPlayAction(sender: AnyObject) {
let fileURL: NSURL = NSURL(string: url)!
let soundData = NSData(contentsOfURL: fileURL)
do {
playerVal = try AVAudioPlayer(data: soundData!)
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down",error)
}
playerVal.delegate = self
playerVal.prepareToPlay()
playerVal.play()
}
Based on #matt answer but little bit detailed 'cause original answer did not completely satisfied me.
import AVFoundation
class YourController: UIViewController {
private var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioPlayer()
}
#IBAction func playAudio() {
player?.play()
}
}
extension YourController: AVAudioPlayerDelegate {}
private extension YourController {
func prepareAudioPlayer() {
guard let path = Bundle.main.path(forResource: "you-audio", ofType:"mp3") else {
return
}
let fileURL = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: fileURL)
} catch let ex {
print(ex.localizedDescription)
}
player?.prepareToPlay()
player?.delegate = self
}
}
swift 3.0:
import UIKit
import AVFoundation
class ViewController: UIViewController
{
var audioplayer = AVAudioPlayer()
#IBAction func Play(_ sender: Any)
{
audioplayer.play()
}
#IBAction func Pause(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.pause()
}
else
{
}
}
#IBAction func Restart(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.currentTime = 0
audioplayer.play()
}
else
{
audioplayer.play()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
do
{
audioplayer = try AVAudioPlayer(contentsOf:URL.init(fileURLWithPath:Bundle.main.path(forResource:"bahubali", ofType: "mp3")!))
audioplayer.prepareToPlay()
var audioSession = AVAudioSession.sharedInstance()
do
{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}
}
catch
{
print (error)
}
}
}
So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?
It would be like this for Objective-C:
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"mysoundname" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);
And then to play it I would do:
AudioServicesPlaySystemSound(Explosion);
Does anyone know how I could do this?
This is similar to some other answers, but perhaps a little more "Swifty":
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Note that this is a trivial example reproducing the effect of the code in the question. You'll need to make sure to import AudioToolbox, plus the general pattern for this kind of code would be to load your sounds when your app starts up, saving them in SystemSoundID instance variables somewhere, use them throughout your app, then call AudioServicesDisposeSystemSoundID when you're finished with them.
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
Handy Swift extension:
import AudioToolbox
extension SystemSoundID {
static func playFileNamed(fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Then, from anywhere in your app (remember to import AudioToolbox), you can call
SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
to play "sound.mp3"
This creates a SystemSoundID from a file called Cha-Ching.aiff.
import AudioToolbox
let chaChingSound: SystemSoundID = createChaChingSound()
class CashRegisterViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
AudioServicesPlaySystemSound(chaChingSound)
}
}
func createChaChingSound() -> SystemSoundID {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
CFRelease(soundURL)
return soundID
}
With a class & AudioToolbox:
import AudioToolbox
class Sound {
var soundEffect: SystemSoundID = 0
init(name: String, type: String) {
let path = NSBundle.mainBundle().pathForResource(name, ofType: type)!
let pathURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
}
func play() {
AudioServicesPlaySystemSound(soundEffect)
}
}
Usage:
testSound = Sound(name: "test", type: "caf")
testSound.play()
import AVFoundation
var audioPlayer = AVAudioPlayer()
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3")
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
audioPlayer.play()
}
}
This code works for me. Use Try and Catch for AVAudioPlayer
import UIKit
import AVFoundation
class ViewController: UIViewController {
//Make sure that sound file is present in your Project.
var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func button1Action(sender: AnyObject) {
audioPlayer.play()
}
}
var mySound = NSSound(named:"Morse.aiff")
mySound.play()
"Morse.aiff" is a system sound of OSX, but if you just click on "named" within XCode, you'll be able to view (in the QuickHelp pane) where this function is searching the sounds. It can be in your "Supporting files" folder
According to new Swift 2.0 we should use do try catch. The code would look like this:
var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
var audioPlayer = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: badumSound)
} catch {
print("No sound found by URL:\(badumSound)")
}
player.prepareToPlay()
this is working with Swift 4 :
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
//Swift 4
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let path = Bundle.main.path(forResource: "note1", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
// error message
}
}
}
Let us see a more updated approach to this question:
Import AudioToolbox
func noteSelector(noteNumber: String) {
if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound)
}
import UIKit
import AudioToolbox
class ViewController: UIViewController {
let toneSound : Array = ["note1","note2","note3","note4","note5","note6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSound(theTone : String) {
if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
var mySound: SystemSoundID = 0
do {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
catch {
print(error)
}
}
}
#IBAction func anypressed(_ sender: UIButton) {
playSound(theTone: toneSound[sender.tag-1] )
}
}
You can try this in Swift 5.2
func playSound() {
let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
For Swift 3:
extension SystemSoundID {
static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Matt Gibson's solution worked for me, here is the swift 3 version.
if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}
Swift 4
import UIKit
import AudioToolbox
class ViewController: UIViewController{
var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...sounds.count-1 {
let fileName : String = "note\(sounds[index])"
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
}
}
}
#IBAction func notePressed(_ sender: UIButton) {
switch sender.tag {
case 1:
AudioServicesPlaySystemSound(sounds[0])
case 2:
AudioServicesPlaySystemSound(sounds[1])
case 3:
AudioServicesPlaySystemSound(sounds[2])
case 4:
AudioServicesPlaySystemSound(sounds[3])
case 5:
AudioServicesPlaySystemSound(sounds[4])
case 6:
AudioServicesPlaySystemSound(sounds[5])
default:
AudioServicesPlaySystemSound(sounds[6])
}
}
}
or
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
}
works in Xcode 9.2
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Swift code example:
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
}
swift 4 & iOS 12
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
// noise while pressing button
_ = Bundle.main.path(forResource: "note1", ofType: "wav")
if Bundle.main.path(forResource: "note1", ofType: "wav") != nil {
print("Continue processing")
} else {
print("Error: No file with specified name exists")
}
do {
if let fileURL = Bundle.main.path(forResource: "note1", ofType: "wav") {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
} else {
print("No file with specified name exists")
}
} catch let error {
print("Can't play the audio file failed with an error \(error.localizedDescription)")
}
audioPlayer?.play() }
}
Use This Function to make sound in Swift (You can use this function where you want to make sound.)
First Add SpriteKit and AVFoundation Framework.
import SpriteKit
import AVFoundation
func playEffectSound(filename: String){
runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
}// use this function to play sound
playEffectSound("Sound File Name With Extension")
// Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")
This code works for me:
class ViewController: UIViewController {
var audioFilePathURL : NSURL!
var soundSystemServicesId : SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav")
AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayAlertSound(sender: UIButton) {
AudioServicesPlayAlertSound(soundSystemServicesId)
}
}
Swift 3 here's how i do it.
{
import UIKit
import AVFoundation
let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as Error {
print(error)
}
}
Couldn't you just import AVFoundation, select the audio player (var audioPlayer : AVAudioPlayer!), and play the sound? (let soundURL = Bundle.main.url(forResource: "sound", withExtension: "wav")