-
-
Save dennisfedorko/143b2a42f7a139b47a44d23a728b0bc0 to your computer and use it in GitHub Desktop.
AVAudioPlayer smart speed to speed up playback during quiet periods in an audio file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ExampleViewController.swift | |
// podcast-ios | |
// | |
// Created by Dennis Fedorko on 3/19/17. | |
// Copyright © 2017 Dennis Fedorko. All rights reserved. | |
// | |
import UIKit | |
import AVFoundation | |
class ExampleViewController: UIViewController { | |
var player: AVAudioPlayer! | |
var amplitudes: [Float] = [] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .white | |
} | |
// Tap screen to start playback | |
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { | |
guard let _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback), | |
let _ = try? AVAudioSession.sharedInstance().setActive(true) else { return } | |
player = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "mp3")!)) | |
player.prepareToPlay() | |
player.addObserver(self, forKeyPath: "rate", options: .new, context: nil) | |
player.isMeteringEnabled = true | |
player.enableRate = true | |
player.play() | |
var timeElapsed = 0.0 | |
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (Timer) in | |
timeElapsed += 0.1 | |
self.player.updateMeters() | |
self.amplitudes.append(self.player.averagePower(forChannel: 0) + 120.0) | |
print("--------") | |
print("min: \(self.amplitudes.min()!)") | |
print("max: \(self.amplitudes.max()!)") | |
print("current: \(self.amplitudes.last!)") | |
print("--------") | |
if self.amplitudes.last! > 50 { | |
self.player.rate = 1.0 + (self.amplitudes.max()! - self.amplitudes.last!) * 0.01 | |
} else { | |
self.player.rate = 1.0 + (self.amplitudes.max()! - self.amplitudes.last!) * 0.02 | |
} | |
print("timeElapsed: \(timeElapsed)") | |
print("playerTimeElapsed: \(self.player.currentTime)") | |
} | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
if keyPath == "rate" { | |
print(player.rate) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To see example work just add to an xcodeproj project, drop in any mp3 file named "test.mp3" to the project, add as rootViewController for window and run the app.
When the view controller is on screen, tap the screen to run the demo.