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
}
}
Related
I am new at swift and Xcode, and When I am trying to play a sound, it gives me an error that I have no idea what is wrong.
This is the code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buttonC(_sender: UIButton) {
playSound()
}
func playSound() {
guard let path = Bundle.main.path(forResource: "C", ofType:"wav") else {
return }
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
}
}
And this is the error:
I will appreciate the help; thanks!
Probably you have renamed your IBAction method name, now it's different and it's connected to the previous name inside your storyboard.
Disconnect your action method and reconnect it appropriately.
Go to your storyboard, select button and then in connectionInspector (cmd + option + 6) delete your previous connection.
Then link your button to the #IBAction function correctly.
I hope it helps you
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 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")
}
}
}
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 :(
}
In my app I have a collectionViewCell that plays music, In the collectionViewCell class I made the player variable
var player: AVAudioPlayer?
I also tried:
var player = AVAudioplayer()
I made a method pauseMusic ()
func pauseMusic (){
if player != nil {
if player!.playing == true{
player!.pause()
}
}
}
When I call this pauseMusic() method from my FirstViewController in the UIBarButtonItem action, my app crashes
#IBAction func pauseButton(sender: UIBarButtonItem) {
var colVW = CollectionViewCell()
colVW.pauseMusic()
}
I also uploaded this screenshot that shows the error when it crashes
http://nl.tinypic.com/r/t66zir/8
Is anybody familiar with this crash?
I would really appreciate if you could give me some advice!
Additional code:
This func checks which song has to be played, this func lives in the CollectionView. Because of the link between this func and the CollectionViewCell class, I can't move the AVPlayer somewhere else..
func prepareAudios() {
var songIndexString = (imageOutlet.titleLabel?.text)!
//println(songIndexString)
var songIndex = (songIndexString.toInt())!
println("songIndex: \(songIndex)")
if musicStopped == true {
rateButton()
println("empty")
} else if var filePath = NSBundle.mainBundle().pathForResource(audioArray[songIndex], ofType: "mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
player = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
player!.play()
} else {
println("Path for audio file not found")
}
}