I am using MusicPlayer & MusicSequence for play .mid file. i want to get Audio duration from .mid file, set Playback Speed on .mid file. i am using below code for play .mid file
var musicPlayer: MusicPlayer?
var sequence: MusicSequence?
func play(file: String) {
guard let midiFile = Bundle.main.url(forResource: file, withExtension: "mid") else {
return
}
NewMusicPlayer(&musicPlayer)
NewMusicSequence(&sequence)
if let musicPlayer = musicPlayer, let sequence = sequence {
MusicSequenceFileLoad(sequence, midiFile as CFURL, .midiType, MusicSequenceLoadFlags())
MusicPlayerSetSequence(musicPlayer, sequence)
MusicPlayerStart(musicPlayer)
}
}
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 have an app in which I want to have a single audio player, and the ability to switch out what audio clips are in the player. Currently using AKAudioPlayer and replace(file: audioFile).
I have the following class that gets created on the view controller loading:
class AudioFilePlayer {
var songFile = Bundle.main
var player: AKAudioPlayer!
func play(file: String, type: String) {
var audioFile: AKAudioFile!
let song = songFile.path(forResource: file, ofType: type)
do {
let url = URL(string: song!)
audioFile = try AKAudioFile(forReading: url!)
} catch {
AKLog(error)
}
do {
player = try AKAudioPlayer(file: audioFile)
} catch {
AKLog(error)
}
}
func rePlay(file: String, type: String) {
var audioFile: AKAudioFile!
let song = songFile.path(forResource: file, ofType: type)
do {
let url = URL(string: song!)
audioFile = try AKAudioFile(forReading: url!)
} catch {
AKLog(error)
}
do {
try player.replace(file: audioFile)
} catch {
AKLog(error)
}
}
func pause(){
player.pause()
}
}
Once the app starts, I have the following code to set up the AK signal chain and create a player with an audio file, and I immediately pause it:
audioFilePlayer.play(file: "Breathing_01", type: ".mp3")
audioFilePlayer.player.looping = false
AudioKit.output = audioFilePlayer.player
do {
try AudioKit.start()
} catch {
AKLog("AudioKit did not start!")
}
audioFilePlayer.player.play()
audioFilePlayer.pause()
Elsewhere in the app, I have the following code to replace the audio file used in the player:
self.audioFilePlayer.player.pause()
self.audioFilePlayer.rePlay(file: "Breathing_01", type: "mp3")
self.audioFilePlayer.player.play()
When I run the app and initiate the process of trying to replace the file, I see this log:
2020-04-05 17:32:13.674413-0700 Mindful[24081:4439478] [general] AKAudioPlayer.swift:replace(file:):397:AKAudioPlayer -> File with "Breathing_01.mp3" Reloaded (AKAudioPlayer.swift:replace(file:):397)
2020-04-05 17:32:13.686119-0700 Mindful[24081:4439478] [general] AKAudioPlayer.swift:startTime:171:AKAudioPlayer.startTime = 0.0, startingFrame: 0 (AKAudioPlayer.swift:startTime:171)
2020-04-05 17:32:14.282632-0700 Mindful[24081:4439478] [general] AKAudioPlayer.swift:updatePCMBuffer():570:read 13359773 frames into buffer (AKAudioPlayer.swift:updatePCMBuffer():570)
But no audio output at all. When setting breakpoints, I can confirm that my player is playing, but have no audio.
Any help appreciated!
I had the same issue. Doing the following fixed it:
try player.replace(file: audioFile)
DispatchQueue.main.async {
self.player.play(from: 0)
}
I am trying to play a list of audios mp3 with AudioKit library. I read about sequencer and I saw all code in the example of official AudioKit Doc.
After calling the method sequencer.play() there is no sound.
var audios:[String] = [
"/Users/rubenpalma/Documents/mp3/hola.mp3",
"/Users/rubenpalma/Documents/mp3/prueba.mp3",
"/Users/rubenpalma/Documents/mp3/mundo.mp3",
"/Users/rubenpalma/Documents/mp3/test.mp3",
"/Users/rubenpalma/Documents/mp3/hi.mp3",
"/Users/rubenpalma/Documents/mp3/adios.mp3"
]
var path = playAudios(background: back, audiosPath: audios)
func playAudios(background:String,audiosPath:[String]) -> String {
var durationBackground = 0.00
let midi = AKMIDI()
let sequencer = AKSequencer()
let mixer = AKMixer()
do{
var i = 0
for path in audiosPath {
let fileAudioURL = NSURL(fileURLWithPath: path)
if let audio = try? AKAudioFile(forReading: fileAudioURL as URL) {
print("\(path) size:\(audio.duration)")
let sampler = AKMIDISampler()
try sampler.loadAudioFile(audio)
sampler.enableMIDI(midi.client, name: "Sampler_\(i)")
mixer.connect(input: sampler)
let track = sequencer.newTrack("t_\(i)")
track?.setMIDIOutput(sampler.midiIn)
track?.add(noteNumber: MIDINoteNumber(i), velocity: 127, position: AKDuration(beats:Double(0)), duration: AKDuration(beats:audio.duration*2), channel:1)
print("is empty? \(track!.isEmpty)")
durationBackground += audio.duration
i += 1
}
}
AudioKit.output = mixer
try AudioKit.start()
sequencer.play()
print("playing.. \(sequencer.isPlaying) ")
}catch{
print("Unexpected non-vending-machine-related error: \(error)")
}
return "duration \(durationBackground)"
}
AKSequencer is to play midi files. To play mp3-files you'd use AKPlayer http://audiokit.io/docs/Classes/AKPlayer.html
I am working with Swift's AVFoundation to launch ultrasonic sinewave and my approach is to play a .wav file. I wonder if there's approach to play the sound continuously instead of using a extra .wav file.
Here follows my code but I don't think the new code will be similar to this:
let myThread = Thread(target: self,
selector: #selector(ZouViewController.play()),
object: nil)
myThread.start()
[...]
func play(){
//rewrite soom
let fileName = Bundle.main.path(forResource: "19kHz", ofType: "wav")
let url = URL(fileURLWithPath: fileName!)
soundPlayer = try? AVAudioPlayer(contentsOf: url)
while true{
soundPlayer?.play()
}
}
The file 19kHz.wav is a sound file playing ultrasonic sinewave at frequency 19kHz, but its duration is not unavoidable. so there would be a sudden change at the begin of sound signal every loop when it is played again. So I want to abandon that approach and try to play the data continuously from a buffer. Is there any way to play a sound signal in a buffer?
I have addressed it by following code:
import Foundation
import AVFoundation
class PlaySineWave{
var audioEngine = AVAudioEngine()
var audioFormat : AVAudioFormat
let FL: AVAudioFrameCount = 44100
let freq : Float = 19000 //19kHz
var pcmBuffer : AVAudioPCMBuffer
init() {
self.audioFormat = AVAudioFormat(standardFormatWithSampleRate: 44100.0, channels: 1)
self.pcmBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat,
frameCapacity:AVAudioFrameCount(FL))
self.pcmBuffer.frameLength = AVAudioFrameCount(FL)
}
func play(){
let floatData = self.pcmBuffer.floatChannelData!.pointee
let step = 2 * Float.pi/Float(FL)
for i in 0 ..< Int(FL) {
floatData[i] = 0.3 * sinf(freq * Float(i) * step)
}
let playerNode = AVAudioPlayerNode()
self.audioEngine.attach(playerNode)
audioEngine.connect(playerNode, to: audioEngine.mainMixerNode,format: pcmBuffer.format)
do {
try audioEngine.start()
} catch let err as NSError {
print("Oh, no! \(err.code) \(err.domain)")
}
playerNode.play()
playerNode.scheduleBuffer(pcmBuffer, at:nil, options: [.loops]) { }
//audioEngine.stop()
}
}
After defined the class, In the ViewController it was called as
override func viewDidLoad() {
[...]
let myThread =
Thread(target:self,selector:#selector(SpectralViewController.play),
object:nil)
myThread.start()
}
[...]
func play(){
var Player = PlaySineWave()
Player.play()
}
I need to playback a single audio file with TheAmazingAudioEngine framework and Swift.
I'm completely newbie with this framework and tried the code below, but the audio didn't play. What is wrong? How could I play the audio file?
do {
var audioController = AEAudioController(audioDescription: AEAudioController.nonInterleavedFloatStereoAudioDescription())
let file = NSBundle.mainBundle().URLForResource("myaudiofile", withExtension: "wav")!
let channel = try AEAudioFilePlayer(URL: file)
audioController?.addChannels([channel])
channel.playAtTime(0)
} catch {
print("Failure")
}
I missed to start the audioController:
do {
var audioController = AEAudioController(audioDescription: AEAudioController.nonInterleavedFloatStereoAudioDescription())
let file = NSBundle.mainBundle().URLForResource("myaudiofile", withExtension: "wav")!
let channel = try AEAudioFilePlayer(URL: file)
audioController?.addChannels([channel])
try audioController!.start()
} catch {
print("Failure")
}