I'm having some issues with getting sound from both of my speakers. I used this code to implement the sound:
if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Is it supposed to only play from one speaker on the computer?
Please be gentle with me, I'm totally new to programming :)
Thanks!
Best regards
Heres is the code, for those who want it:
import UIKit
import AudioToolbox
class ViewController: UIViewController{
let soundArray = ["note1", "note2", "note3", "note4", "note5", "note6", "note7"]
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
playingSound(soundFileName: soundArray[sender.tag - 1])
}
func playingSound(soundFileName : String) {
if let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
}
}
Related
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'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()
}
I am trying to play a sound in my iOS app (written in Swift 2) using AVFoundation. I had it working with no issues with the previous version of Swift. I am using Xcode 7.0. I am not sure what the issue is and cannot find any additional info for Swift 2 regarding playing sounds. Here's my code for the sound part:
import AVFoundation
class ViewController: UIViewController {
var mySound = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
mySound = self.setupAudioPlayerWithFile("mySound", type:"wav")
mySound.play()
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
}
I am getting this error but have a feeling there maybe some other issue:
'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?
Like Leo said
You need to implement do try catch error handling.
Here is another example of some code that will run sound when a button is pressed.
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBAction func play(sender: AnyObject) {
player.play()
}
#IBAction func pause(sender: AnyObject) {
player.pause()
}
var player: AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("sound", ofType: "mp3")!
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
} catch {
// Process error here
}
}
}
I hope this helps!
You need to implement do try catch error handling. Try like this:
func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {
if let url = NSBundle.mainBundle().URLForResource(file, withExtension: type) {
do {
return try AVAudioPlayer(contentsOfURL: url)
} catch let error as NSError {
print(error.localizedDescription)
}
}
return nil
}
I am trying to play an audio file using the AVAudioEngine. I have seen several examples, and I'm just following the same steps. However, the sound is not being played. Here's my code:
var audioUrl = NSURL(fileURLWithPath: "my-path-to-audio-file")
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
audioEngine.attachNode(myPlayer)
var audioFile = AVAudioFile(forReading: audioUrl, error: nil)
var audioError: NSError?
audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&audioError)
myPlayer.play()
The reason I am not simply using AVAudioPlayer is because I need to add later some effects.
Can anyone please help me out with that?
Thanks!
I ran your code, and it worked fine, there are three things I would check:
Make sure your file is found, so change your code to work with AVAudioPlayer just to check that the program knows where the file is, and that it can play it
Second, check where you are putting your statements, my example with the code is below.
import UIKit
import AVFoundation
class aboutViewController: UIViewController {
var audioUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("chimes", ofType: "wav")!)
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
audioEngine.attachNode(myPlayer)
var audioFile = AVAudioFile(forReading: audioUrl, error: nil)
var audioError: NSError?
audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&audioError)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func testSound(sender: AnyObject) {
myPlayer.play()
}
}
Hope this helps, ask if you have any questions!