How to play audio in simulator? - ios

import UIKit
import SwiftUI
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
}
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
let player = AVPlayer.init(url: url!)
player.play()
print(url!)
}
}
file:///Users/user/Library/Developer/CoreSimulator/Devices/C3333006-1A90-4B12-A9F6-E04B3603334C/data/Containers/Bundle/Application/265FB456-9524-44DY-B669-D67ACB7F444C/Xylophone.app/D.wav
I'm trying to play sound, which are already in the package folder, but failed to do so in simulator, can't play any sound even if unmute and increase sound volume of the simulator and my Mac.

I use this code and it works:
let jingleURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "jingle", ofType: ".mp3")!)
let jingleAVPlayer = AVPlayer.init(url: jingleURL)
jingleAVPlayer.play()
The filename is jingle.mp3 and is added in Xcode.
I hope this helps you out ;)

Related

Play random sounds from my projects in Swift 5

I'm new in iOS. I have written this code, which plays only one audio file when tapping a UIButton. I would like to play multiple sound randomly. How to set it? Thank you!
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
#IBAction func playButtonPressed(_ sender: UIButton) {
if let soundURL = Bundle.main.url(forResource: "kompilacja", withExtension: "mp3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}else{
print("Karwasz twarz! Brak pliku audio, Panie!")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Put all of your sound file names in an array and use the randomElement method to choose your sound.
#IBAction func playButtonPressed(_ sender: UIButton) {
let sounds = ["kompilacja", "another sound", "yet another sound"]
guard let sound = sounds.randomElement(),
let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}

Swift: How to stop Background music when changing views

I'm trying to get the background music to stop playing when changing to another view.
I have a global variable to play the music
import Foundation
import AVFoundation
class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?
func playBackgroundMusic() {
let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "The Walking Dead", ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
audioPlayer!.numberOfLoops = -1
audioPlayer!.prepareToPlay()
audioPlayer!.play()
} catch {
print("Cannot play the file")
}
}
}
And then I load the music into the view here
import UIKit
import SwiftGifOrigin
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
#IBOutlet weak var introGif: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Gif intro
self.introGif.image = UIImage.gifWithName("WalkingDeadIntro")
_ = try! Data(contentsOf: Bundle.main.url(forResource: "WalkingDeadIntro", withExtension: "gif")!)
//self.bottomImageView.image = UIImage.gif(data: imageData)
// Load background Music
MusicHelper.sharedHelper.playBackgroundMusic()
}
Just write below code to stop the player whenever view changes provided that audioPlayer is a global variable as you mentioned.
override func viewWillDisappear( ) {
audioPlayer.stop( )
}

AVFoundation - Music iOS

I have been trying to add music to my application without particular success. I have been trying to use AVFoundation and my code is the following:
//MUSIC
var audioPlayer = AVAudioPlayer()
let audioPath = Bundle.main.path(forResource: "happyDays", ofType: "wav")
do {
try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!))
}
catch {
// process error
}
audioPlayer.play()
I do not get any error but my application boots and no music plays. Can anyone help?
swift 3
import UIKit
import AVFoundation
class ViewController: UIViewController{
let var avPlayer: AVAudioPlayer!
#IBAction func btnPlayPauseAudio(_ sender: UIButton){
if self.avPlayer != nil{
if let myAudioUrl = Bundle.main.url(forResource: "myAudioFile", withExtension: "mp3"){
if self.avPlayer.isPlaying{
self.avPlayer.pause()
}
else{
self.avPlayer = try AVAudioPlayer(contentsOf: myAudioUrl)
self.avPlayer.prepareToPlay()
self.avPlayer.play()
}
}
}
}
}

Error when trying to play video in Xcode 7 / Swift 2

I am trying to play a video inside a view controller when I enter it, but a get one error, listed below.Not too familiar with video playback, so is it supposed to be in a viewcontroller and how do I fix that error?The video is stored in xcode. Thanks.
import UIKit
import MediaPlayer
import AVFoundation
class AuroraViewController: UIViewController {
#IBOutlet var AuroraViewController: UIView!
var moviePlayer: AVPlayer?
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType:"mp4") {
let url = NSURL(fileURLWithPath: path)
The line below is where I get the error of: Type of expression is ambiguous without more context
moviePlayer = AVPlayer(contentURL: url) {
self.moviePlayer = moviePlayer
moviePlayer.AuroraViewController.frame = self.AuroraViewController.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
self.AuroraViewController.addSubview(moviePlayer.view)
}
} else {
debugPrint("Ops, something wrong when playing video.m4v")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
playVideo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
UPDATE Correct code:
import UIKit
import AVFoundation
import AVKit
class AuroraViewController: AVPlayerViewController {
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
}
else {
println("Oops, could not find resource Aurora.mp4")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
}
This was a 'total re-write'.
The following did the job:
Add "AVKit.framework" to the "Build Phases" -> "Link Binary With Libraries" in Project settings.
In Storyboard, change the identity of your UIViewController to be AuroraViewController.
The resulting code then is all that's needed:
import UIKit
import AVFoundation
import AVKit
class AuroraViewController: AVPlayerViewController {
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
}
else {
println("Oops, could not find resource Aurora.mp4")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
}

Playing a sound with AVAudioPlayer

I'm trying to play a sound with AVAudioPlayer but it won't work.
Edit 1: Still doesn't work.
Edit 2: This code works. My device was in silent mode.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Made modification to your code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
// Removed deprecated use of AVAudioSessionDelegate protocol
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()
}
}
Swift 3 and Swift 4.1:
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!)
print(alertSound)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
}
As per Swift 2 the code should be
var audioPlayer : AVAudioPlayer!
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()//there is also an async version
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
Your audio play will be deallocated right after viewDidLoad finishes since you assign it to a local variable. You need to create a property for it to keep it around.
The solution is for AudioPlayer which has play/pause/stop button in the navigation bar as bar button items
In Swift 2.1 you can use the below code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3")
var error:NSError? = nil
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down")
}
}
#IBAction func play(sender: UIBarButtonItem) {
player.play()
}
#IBAction func stop(sender: UIBarButtonItem) {
player.stop()
print(player.currentTime)
player.currentTime = 0
}
#IBAction func pause(sender: UIBarButtonItem) {
player.pause()
}
#IBOutlet weak var sliderval: UISlider!
#IBAction func slidermov(sender: UISlider) {
player.volume = sliderval.value
print(player.volume)
}
}
This will work.....
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ding:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
prepareAudios()
ding.play()
}
func prepareAudios() {
var path = NSBundle.mainBundle().pathForResource("ding", ofType: "mp3")
ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil)
ding.prepareToPlay()
}
}
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 is a pretty old question, but I did not see an answer that worked with Swift 3.0 so I modernized the code and added some safety checks to prevent crashes.
I also took the approach of pulling the playing part out into its own function to help with re-use for anyone coming across this answer.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
play(for: "button-09", type: "wav")
}
func play(for resource: String, type: String) {
// Prevent a crash in the event that the resource or type is invalid
guard let path = Bundle.main.path(forResource: resource, ofType: type) else { return }
// Convert path to URL for audio player
let sound = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: sound)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
} catch {
// Create an assertion crash in the event that the app fails to play the sound
assert(false, error.localizedDescription)
}
}
}
Swift 4.2 onwards, AudioSession category setup options have been changed. (Try following code for Swift 4.2 onwards)
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioSession()
}
func prepareAudioSession() -> Void {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true)
prepareAudioPlayer()
} catch {
print("Issue with Audio Session")
}
}
func prepareAudioPlayer() -> Void {
let audioFileName = "test"
let audioFileExtension = "mp3"
guard let filePath = Bundle.main.path(forResource: audioFileName, ofType: audioFileExtension) else {
print("Audio file not found at specified path")
return
}
let alertSound = URL(fileURLWithPath: filePath)
try? audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer?.prepareToPlay()
}
func playAudioPlayer() -> Void {
audioPlayer?.play()
}
func pauseAudioPlayer() -> Void {
if audioPlayer?.isPlaying ?? false {
audioPlayer?.pause()
}
}
func stopAudioPlayer() -> Void {
if audioPlayer?.isPlaying ?? false {
audioPlayer?.stop()
}
}
func resetAudioPlayer() -> Void {
stopAudioPlayer()
audioPlayer?.currentTime = 0
playAudioPlayer()
}
}

Resources