Trying play AMR audio file using this code:
var player: AVAudioPlayer? = nil
WebService.shared.download(self.dataSource.object(at: indexPath)) { data in
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
guard let player = player else { return }
print("Going to play: \(player.duration) seconds...")
player.volume = 1.0
player.prepareToPlay()
player.play()
} catch {
print(error.localizedDescription)
}
}
I'm absolutely sure that:
data received is not nil
I can see correct duration time of amr file
amr files contains some voices
I did not get any error's
I did not hear anything
What's up and how fix it?
The problem is with
guard let player = player else { return }
You are replacing the outer, optional AVAudioPlayer with a non-optional local copy. You call play() on the local copy and then when the closure completes, it goes out of scope and is deleted.
Try this.
player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
player?.volume = 1.0
player?.prepareToPlay()
player?.play()
} catch {
Related
I'm trying to play a file I downloaded from S3, after locating the file and passing the URL to the audio player, the audio file won't play/is missing.
This is the complete fileURL: file:///var/mobile/Containers/Data/Application/61F2FC20-4C62-4263-B147-0010805BC0FA/Documents/Dump%20Trucks.mp3
Here is my code:
func playAudio(){
var soundClip: AVAudioPlayer?
if let directory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first{
let path = NSURL(fileURLWithPath: directory).appendingPathComponent("Dump Trucks.mp3")
print("The path is \(String(describing: path))")
do {
soundClip = try AVAudioPlayer(contentsOf: path!)
soundClip?.play()
} catch {
print("Error: Audio File missing.")
}
}
}
The problem is that your player is a local variable. Thus your method comes to an end and the player is destroyed before it ever has a chance to start playing! Declare it as an instance property instead.
So
func playAudio(){
var soundClip: AVAudioPlayer?
Becomes
var soundClip: AVAudioPlayer?
func playAudio(){
This might not solve all your problems but if you don’t do it you certainly will never hear sound.
import Foundation
import AVFoundation
final class MediaPlayer {
static var player = AVAudioPlayer()
class func play() {
do {
let file = Bundle.main.url(forResource: "file_name", withExtension: "mp3")!
player = try AVAudioPlayer(contentsOf: file)
player.numberOfLoops = 0 // loop count, set -1 for infinite
player.volume = 1
player.prepareToPlay()
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true)
player.play()
} catch _ {
print("catch")
}
}
}
I'm using Xcode 7.3.1 with iOS 9 and having issue with playing sound by AVAudioPlayer. I've tried all possible solution out there and nothing works Here is my code
let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!
var player = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: mp3Url)
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
The sound won't play until I put a breakpoint at player.play() and using po player. Then the sound will be played.
Any idea will be helpful for me.
Try this :
var player: AVAudioPlayer?
func playSound(){
guard let url = Bundle.main.url(forResource: "alert_song", withExtension: "mp3") else {
print("MP3 resource not found.")
return
}
print("Music to play : \(String(describing: url))")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Try this :
var player = AVAudioPlayer() //global variables will otherwise be deadlock
let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: mp3Url)
player.play()
} catch let error as NSError {
print(error.description)
}
Currently this is the code I'm using to play my sound during the button press.
var player: AVAudioPlayer?
let url = Bundle.main.url(forResource: "Sound/yatch", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
Im trying to get this audio to run over whats currently playing (etc Spotify, pandora, Music). How would I go about doing this?
Set the audio session of your application to play over the currently playing audio:
try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
According to the AVAudioSession headers, AVAudioSessionCategoryAmbient will play audio with music, etc.
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String
Swift 5.3 Update
guard let url = Bundle.main.url(forResource: "INSERT_FILENAME", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
audioPlayer.volume = 1
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
Hey guys so for some reason when you mute the phone the audio is still coming from the app. Any ideas on how to fix?
private func myFunc() {
// Set up the audio session
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
fatalError("Unable to set the audio session because: \(error)")
}
guard
let audioURL = Bundle.main.url(forResource: "lololol", withExtension: "mp3"),
let player = try? AVAudioPlayer(contentsOf: audioURL)
else { fatalError("Unable to create player") }
if let aPlayer = audioPlayer {
if audioPlayer?.isPlaying == false {
audioPlayer = player
player.play()
}
} else {
audioPlayer = player
player.play()
}
}
I solve it by changing AVAudioSessionCategoryPlayback to AVAudioSessionCategoryAmbient.
I need play audio sound file from user local file system container in iOS using Swift like
file:///Users/User/Library/Developer/CoreSimulator/Devices/EE8A846B-56D9-4B2B-9B52-FCC5CC16B7CA/data/Containers/Data/Application/C057C9A4-77DB-4615-AA78-C0A256ECD2D2/Documents/Dumont.mp3
Try This
//give your file path here in form of url
let urlstring = "file:///Users/User/Library/Developer/CoreSimulator/Devices/EE8A846B-56D9-4B2B-9B52-FCC5CC16B7CA/data/Containers/Data/Application/C057C9A4-77DB-4615-AA78-C0A256ECD2D2/Documents/Dumont.mp3"
let url = NSURL(string: urlstring)
do
{
self.player = try AVAudioPlayer(contentsOfURL: url)
player.prepareToPlay()
player.volume = 1.0
player.play()
}
catch let error as NSError
{
print(error.localizedDescription)
}
catch {
print("AVAudioPlayer init failed")
}