I have started to learn ios development and am stuck in one place. My code to play mp3 file is
var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
bombSoundEffect.play()
} catch {
print("couldn't load file :(")
}
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
However, when I click on the button, my file doesn't play. The song is playing perfectly normally.
Try with the follow code:
var bombSoundEffect: AVAudioPlayer?
func playAudio() {
let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!
do {
bombSoundEffect = try AVAudioPlayer(contentsOf: url)
guard let bombSound = bombSoundEffect else { return }
bombSound.prepareToPlay()
bombSound.play()
} catch let error {
print(error.localizedDescription)
}
}
There's lots wrong with your code, but it's a sunny day, so try something like this…
func playSound() {
guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }
let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
bombSoundEffect?.play()
}
Related
I am a total swift beginner and am working on a tutorial project (magic 8 ball) and have been successful at doing the following:
- play a specific sound when the "Ask" button is pressed.
- play a specific sound when for each of the randomly picked images
However now the sound that should play whenever the button is pressed only plays once and from there on i only hear the sounds that are being displayed with each image. Is this because I am "stuck" in the "if - else" loop ? Or do I have to delay the sounds that are being played for each image in the array ?
Thanks so much for your help !
Here is my code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var magicBall: UIImageView!
var magicBallDisplay = 1
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
}
#IBAction func askButtonPressed(_ sender: UIButton) {
let magicBallArray = [ #imageLiteral(resourceName: "askagainlater"),#imageLiteral(resourceName: "no"),#imageLiteral(resourceName: "theanswerisyes"),#imageLiteral(resourceName: "yes"),#imageLiteral(resourceName: "noidea")]
magicBall.image = magicBallArray.randomElement()
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Ask", ofType: "wav")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
}catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
if (magicBall.image?.isEqual(UIImage(named: "yes")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "yes", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "no")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "no", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "theanswerisyes")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "theanswerisyes", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "noidea")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "noidea", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
else if (magicBall.image?.isEqual(UIImage(named: "askagainlater")))! {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "askagainlater", ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
}
I make a new project and change your code to this:
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var magicBall: UIImageView!
// you never used this
//var magicBallDisplay = 1
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
}
#IBAction func askButtonPressed(_ sender: UIButton) {
// because you have audio file and image with equal name i made array of string
let magicBallArray = [ "yes","no","theanswerisyes","noidea","askagainlater"]
// check if i get not null item
guard let choosedImageName = magicBallArray.randomElement() else {return}
print(choosedImageName)
// set image with random picked name
magicBall.image = UIImage(named: choosedImageName)
// play ask sound
playSound(fileName: "Ask", fileType: "wav")
// play picked image sound after 10 second from now()
// change number to your needed time
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.playSound(fileName: choosedImageName, fileType: "mp3")
})
}
private func playSound(fileName: String, fileType: String)
{
// check if you find the audio file
guard let url = Bundle.main.path(forResource: fileName, ofType: fileType) else {
print("path not found")
return
}
// make NSURL from path
let soundURL = NSURL(fileURLWithPath: url)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
} catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
I explain code for you.
I didn't enable the button. you can improve this code when you came stronger in swift
your code is really messy.
at first, I advise you to make a function for playing sound like that:
func playSound(fileName: String, fileType: String) {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: fileName, ofType: fileType)!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
}catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
you must have a callback for first play sound. after finishing the first sound you can check your if-else or you can try switch-case.
also, you can use delay for playing second sound
I was trying to read a file xyz.m4a and trying to play it. But I have an error
2018-04-24 18:11:20.010927+0530 Demo[10807:690526] NSURLConnection finished with error - code -1002
2018-04-24 18:11:20.327008+0530 Demo[10807:688427] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
Error: The file “xyz.m4a” couldn’t be opened.
Here is my code:
func audioMethod() {
let fileName = "xyz.m4a",
audioFile = getDocumentsURL().appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: audioFile.path) {
print("We have no file !!!!!")
}
do {
let audioData = try Data(contentsOf: audioFile)
if audioPlayer == nil {
audioPlayer = try AVAudioPlayer.init(data: audioData, fileTypeHint: "m4a")
}
audioPlayer?.play()
} catch let error {
print("Error: " + error.localizedDescription)
}
}
func getDocumentsURL() -> URL {
let urlStr = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let url = URL(string: urlStr!)
return url!
}
If I pass that URL direct in AVAudioPlayer as AVAudioPlayer.init(contentsOf: audioFile) then it works fine.
I have tried everything. But nothing works. Please let me know what is wrong with my code.
if let path = Bundle.main.path(forResource: "videoplayback", ofType: "mp4"){
let video = AVPlayer(url: URL(fileURLWithPath:path))
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
present(videoPlayer,animated: true,completion: {
video.play()
})
}
Add that Video in File Explorer
Then try with above code
I am trying to play a sound but my current code bases the volume off of the ringtone volume. How to I change this to media volume?
var player: AVAudioPlayer?
...
func playSound(name: String) {
let url = Bundle.main.url(forResource: name, withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
...
playSound(name: "baby")
Only set that before you put some url into the player.
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
To play sound using media volume you should do like this:
func play(){
let path = Bundle.main.path(forResource: "Plop", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.play()
} catch {
// couldn't load file :(
}
}
So basically I have two audio players while using the AVFoundation. I want the second one to be played right after the first one finishes.
myFilePathString = NSBundle.mainBundle().pathForResource("\(workout[currentExercise])", ofType: "mp3")
#IBAction func startWorkout(sender: AnyObject) {
if let myFilePathString = myFilePathString {
let myFilePathURL = NSURL(fileURLWithPath: myFilePathString)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: myFilePathURL)
audioPlayer.play()
}catch {
print("Error")
}
}
This above one is to be the first
let path = NSBundle.mainBundle().pathForResource("Rest", ofType: "mp3")
let url = NSURL(fileURLWithPath: path!)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
secondAudioPlayer = sound
sound.play()
} catch {
print("error")
}
...while this one is to be played after. At the moment they play at the same time. Got any ideas for me?
Thank you in advance.
i try to make iOS app to play some funny sound put when i click play no sound are out from speaker here is the code :
#IBAction func slow(sender: UIButton) {
if let filePath = NSBundle.mainBundle().URLForResource("io", withExtension: "mp3") {
let _a = try! AVAudioPlayer(contentsOfURL: filePath)
// Play
_a.play()
}else
{
print("error")
}
}
there is no error but i can't hear any sound at all
for how that face this problem
#IBAction func slow(sender: UIButton) {
if let path = NSBundle.mainBundle().pathForResource("io", ofType:"mp3") {
let fileURL = NSURL(fileURLWithPath: path)
player = try! AVAudioPlayer(contentsOfURL: fileURL)
player.prepareToPlay()
player.play()
}
else
{
print("error")
}
}
}