I want to make it so that a button can be clicked, which will start repeatedly playing a system sound over and over (without overlapping the sounds) until the button is clicked again - so essentially, the button will toggle the repeated playing of an audio services system sound on/off.
If anyone would know how to do this I would greatly appreciate it.
Thanks
To do this use an AVAudioplayer with infinite repeat, and then pause/play it when button is pressed.
First make a audioPlayer variable, outside of any function:
var audioPlayer : AVAudioPlayer!
Then initialise the audioPlayer inside of viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
guard let url = Bundle.main.path(forResource: "myOwnSound", ofType: "wav") else { //your own file name AND extension type of course
print("file not found")
return
}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: URL(string: url)!)
audioPlayer!.prepareToPlay()
audioPlayer.numberOfLoops = -1
} catch let error as NSError {
print("error while initialising sound: \(error)")
}
}
Then inside a function linked to your button, in my case I named that function buttonPressed:
#IBAction func buttonPress(_ sender:AnyObject){
if audioPlayer.isPlaying {
audioPlayer.pause()
}
else {
audioPlayer.play()
}
}
You can use AVFoundation and AVAudioPlayer to manage music and
sound inside you application
Import following
import AVFoundation
Create a property of AVAudioPlayer to manage play/stop and add following code inside the scope of your music button
var player : AVAudioPlayer?
#IBAction func openListAction(_ sender: UIButton) {
// moveToGame()
if sender.isSelected {
sender.isSelected = false
player?.stop()
}
else {
sender.isSelected = true
let bundle = Bundle.init(for: self.classForCoder)
let path = bundle.path(forResource: "soundFileName", ofType : "soundFileExtension")! //.mp3, .caf etc
let url = URL(fileURLWithPath : path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
print ("Error to load music")
}
}
}
Related
I am making a very simple IOS app. It is a button, and when pressed a long .wav file plays. I would love to be able to press the button again, and the audio would stop playing. I’ve tried many of the solutions here as there are similar questions, but I’m stuck. Any ideas?
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Making a variable called player. It is the AVAudioPlayer
var player: AVAudioPlayer!
// No idea what this is.
override func viewDidLoad() {
super.viewDidLoad()
}
//This is the key pressed. Inside is the playSound and a print for checking
#IBAction func keyPressed(_ sender: UIButton) {
playSound()
print("button pressed")
}
//Turn playSound into a func – and tell it what to play and play it if button is pressed
func playSound() {
let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
AVAudioPlayer has the isPlaying (docs) property that you can check to determine if you should play or stop playback when your button is pressed.
import AVFoundation
import UIKit
class ViewController: UIViewController {
// Making a variable called player. It is the AVAudioPlayer
var player: AVAudioPlayer!
// This is the key pressed. Inside is the playSound and a print for checking
#IBAction func keyPressed(_ sender: UIButton) {
if player.isPlaying {
stopSound()
} else {
playSound()
}
}
// Turn playSound into a func – and tell it what to play and play it if button is pressed
func playSound() {
let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
func stopSound() {
player.stop()
}
}
Sidenote: The viewDidLoad method override isn't needed unless you're wanting to have custom code run when the view is loaded by the system.
I am trying to determine if a user taps on the unmute button while watching a video. I am aware of player.isMuted but I am not sure how to check if there is a change if value. I am using AVPlayerVideoViewController and want to override the unmute button functionality.
I created a sample ViewController, you can observe isMuted changes easily:
import AVKit
class ViewController: AVPlayerViewController {
var muteObservation: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
guard let videoPath = Bundle.main.path(forResource: "video", ofType: "mov") else {
return
}
let videoURL = URL(fileURLWithPath: videoPath)
player = AVPlayer(url: videoURL)
player?.play()
muteObservation = player?.observe(\.isMuted) { player, _ in
print("isMuted: \(player.isMuted)")
}
}
}
I have added background music to my app using the following code:-
Now I am trying to add audio controls to my app using the following methods, but after I click on another view controller and come back to the main view controller the play button is not working. Any help will be highly appreciated Thanks!
var toggleState = 1
var music: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playMusic()
}
func playMusic() {
if let musicURL = Bundle.main.url(forResource: "Adding", withExtension: "mp3") {
if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
music = audioPlayer
music.numberOfLoops = -1
music.play()
}
}
}
#IBAction func playButtonPressed(_ sender: Any) {
if (toggleState == 1) {
music.pause()
toggleState = 2
}
else {
music.play()
toggleState = 1
}
}
I am trying to have a button that will play a sound when pushed.
The app I have has 6 buttons (with 6 different sounds). I only have one listed because I am trying to get one button to work correctly before doing the rest. I know the button is working (from the print command at the bottom), but it is not playing the sound.
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
var player : AVAudioPlayer?
#IBAction func buttonOne(_ sender: Any) {
func playSound() {
let url = Bundle.main.url(forResource: "drinking", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
print("Anakin: IT IS WORKING!")
}
}
Is it printing any error?
Can you try doing this?
let path = Bundle.main.path(forResource: "FILE NAME WITH EXTENSION", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
sound.play()
} catch {
// couldn't load file :(
}
I'm trying to add sound to an iOS app that I am writing. I keep getting the error message
"Incorrect argument label in call (have 'contentsOfURL:error:', expected "contentsOfURL:fileTypeHint:')".
I have tried tinkering with it in several ways, and I can't get it to build. Here is my code:
import UIKit import AVFoundation
class ViewController: UIViewController {
var Setup = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("DMSetup", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
audioPlayer = AVAudioPlayer(contentsOfURL: Setup, error: nil)
audioPlayer.prepareToPlay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayKeySetup(sender: UIButton) {
audioPlayer.play()
}
}
Any suggestions? I'm a newbie at this, so I'm sure I'm missing something obvious.
xCode 7.3.1, OSX 10.11.4
Thanks.
Try this code:
var audioPlayer: AVAudioPlayer!
let path = NSBundle.mainBundle().pathForResource("yourfilename", ofType: "format")
let CREATE_ANY_VARIABLE = NSURL(fileURLWithPath: path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: CREATE_ANY_VARIABLE)
} catch let error as NSError {
print(error.debugDescription)
}
audioPlayer.prepareToPlay()
and then you can play anywhere in the function!
the problem in your code is the name of your var Setup is overlapping with another Setup method form the AVFoundation
Usually using uppercase to the properties name it's considered as a bad attitude, you should use setup
Try this code:
let setupUrl = NSBundle.mainBundle().URLForResource("DMSetup", withExtension: "mp3")
if (setupUrl == nil) {
print("Could not find file: DMSetup.mp3")
return
}
do { audioPlayer = try AVAudioPlayer(contentsOfURL: Setup!, fileTypeHint: nil) }
catch let error as NSError { print(error.description) }
if let player = audioPlayer {
player.prepareToPlay()
}