kandi background
Explore Kits

AudioFile | A simple C library for reading and writing audio files. | Audio Utils library

 by   adamstark C++ Version: Current License: MIT

 by   adamstark C++ Version: Current License: MIT

Download this library from

kandi X-RAY | AudioFile Summary

AudioFile is a C++ library typically used in Audio, Audio Utils applications. AudioFile has no bugs, it has a Permissive License and it has low support. However AudioFile has 14 vulnerabilities. You can download it from GitHub.
A simple header-only C++ library for reading and writing audio files.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • AudioFile has a low active ecosystem.
  • It has 541 star(s) with 130 fork(s). There are 17 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 6 open issues and 28 have been closed. On average issues are closed in 169 days. There are 4 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of AudioFile is current.
AudioFile Support
Best in #Audio Utils
Average in #Audio Utils
AudioFile Support
Best in #Audio Utils
Average in #Audio Utils

quality kandi Quality

  • AudioFile has no bugs reported.
AudioFile Quality
Best in #Audio Utils
Average in #Audio Utils
AudioFile Quality
Best in #Audio Utils
Average in #Audio Utils

securitySecurity

  • AudioFile has 14 vulnerability issues reported (0 critical, 2 high, 12 medium, 0 low).
AudioFile Security
Best in #Audio Utils
Average in #Audio Utils
AudioFile Security
Best in #Audio Utils
Average in #Audio Utils

license License

  • AudioFile is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
AudioFile License
Best in #Audio Utils
Average in #Audio Utils
AudioFile License
Best in #Audio Utils
Average in #Audio Utils

buildReuse

  • AudioFile releases are not available. You will need to build from source code and install.
  • Installation instructions are not available. Examples and code snippets are available.
AudioFile Reuse
Best in #Audio Utils
Average in #Audio Utils
AudioFile Reuse
Best in #Audio Utils
Average in #Audio Utils
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

AudioFile Key Features

WAV

AIFF

Create an AudioFile object:

copy iconCopydownload iconDownload
#include "AudioFile.h"

AudioFile<double> audioFile;

Load an audio file:

copy iconCopydownload iconDownload
audioFile.load ("/path/to/my/audiofile.wav");

Get some information about the loaded audio:

copy iconCopydownload iconDownload
int sampleRate = audioFile.getSampleRate();
int bitDepth = audioFile.getBitDepth();

int numSamples = audioFile.getNumSamplesPerChannel();
double lengthInSeconds = audioFile.getLengthInSeconds();

int numChannels = audioFile.getNumChannels();
bool isMono = audioFile.isMono();
bool isStereo = audioFile.isStereo();

// or, just use this quick shortcut to print a summary to the console
audioFile.printSummary();

Access the samples directly:

copy iconCopydownload iconDownload
int channel = 0;
int numSamples = audioFile.getNumSamplesPerChannel();

for (int i = 0; i < numSamples; i++)
{
	double currentSample = audioFile.samples[channel][i];
}

Replace the AudioFile audio buffer with another

copy iconCopydownload iconDownload
// 1. Create an AudioBuffer 
// (BTW, AudioBuffer is just a vector of vectors)

AudioFile<double>::AudioBuffer buffer;

// 2. Set to (e.g.) two channels
buffer.resize (2);

// 3. Set number of samples per channel
buffer[0].resize (100000);
buffer[1].resize (100000);

// 4. do something here to fill the buffer with samples, e.g.

#include <math.h> // somewhere earler (for M_PI and sinf())

// then...

int numChannels = 2;
int numSamplesPerChannel = 100000;
float sampleRate = 44100.f;
float frequency = 440.f;

for (int i = 0; i < numSamplesPerChannel; i++)
{
    float sample = sinf (2. * M_PI * ((float) i / sampleRate) * frequency) ;
    
    for (int channel = 0; channel < numChannels; channel++)
         buffer[channel][i] = sample * 0.5;
}

// 5. Put into the AudioFile object
bool ok = audioFile.setAudioBuffer (buffer);

Resize the audio buffer

copy iconCopydownload iconDownload
// Set both the number of channels and number of samples per channel
audioFile.setAudioBufferSize (numChannels, numSamples);

// Set the number of samples per channel
audioFile.setNumSamplesPerChannel (numSamples);

// Set the number of channels
audioFile.setNumChannels (int numChannels);

Set bit depth and sample rate

copy iconCopydownload iconDownload
audioFile.setBitDepth (24);
audioFile.setSampleRate (44100);

Save the audio file to disk

copy iconCopydownload iconDownload
// Wave file (implicit)
audioFile.save ("path/to/desired/audioFile.wav");

// Wave file (explicit)
audioFile.save ("path/to/desired/audioFile.wav", AudioFileFormat::Wave);

// Aiff file
audioFile.save ("path/to/desired/audioFile.aif", AudioFileFormat::Aiff);

A Note On Types

copy iconCopydownload iconDownload
AudioFile<float> audioFile;

Error Messages

copy iconCopydownload iconDownload
audioFile.shouldLogErrorsToConsole (false);

Inno Setup Music Glitches when exiting

copy iconCopydownload iconDownload
procedure DeinitializeSetup();
begin
  if (SoundStream <> 0) and
     (BASS_ChannelIsActive(SoundStream) <> BASS_ACTIVE_PAUSED) then
  begin
    BASS_ChannelPause(SoundStream);
  end;

  // Hide Window before unloading skin so user does not get
  // a glimpse of an unskinned window before it is closed.
  ShowWindow(StrToInt(ExpandConstant('{wizardhwnd}')), 0);
  UnloadSkin();
end;

Play button in HTML form not playing the latest audio file, plays an old version that is meant to have been overwritten

copy iconCopydownload iconDownload
function playAudio() {
  var audioFile = new Audio('./speech.wav?' + new Date().getTime());
  audioFile.play()
}

Vue: click to play audio, click again to pause for multiple tracks

copy iconCopydownload iconDownload
changeSong: function(index) {

  // a song is playing/paused and it's clicked again
  if (this.currentSong != null && this.currentSong === index) {
     // want to pass 0 through^ since it's legit index
    if (this.audio.paused) {
      return this.audio.play()
    } else {
      return this.audio.pause()
    };
    // ^ returns from from the function in case of play/pause existing song
  }

  // --- a new song is clicked ---

  // pause current song before losing reference to it.
  this.audio.pause()

  this.currentSong = index;
  this.audioFile = this.musicPlaylist[this.currentSong].url;
  this.audio = new Audio(this.audioFile);

  /* not sure if this is needed anymore.
   * Does audio start playing automatically? Remove if not needed
   */

  if (this.audio.paused) {
    this.audio.play()
  }
},

Cut .mp4 in pieces Python

copy iconCopydownload iconDownload
ffmpeg -i source-file.foo -ss 0 -t 600 first-10-min.m4v
ffmpeg -i source-file.foo -ss 600 -t 600 second-10-min.m4v
ffmpeg -i source-file.foo -ss 1200 -t 600 third-10-min.m4v
splitLength = 5
for i in range(int(videoLength/splitLength)):
    start =i*60
    length=splitLength*60 
    os.system("ffmpeg -i source-file.foo -ss " + str(start) + " -t " + str(length) + " clip"+str(i)+".m4v")
-----------------------
ffmpeg -i source-file.foo -ss 0 -t 600 first-10-min.m4v
ffmpeg -i source-file.foo -ss 600 -t 600 second-10-min.m4v
ffmpeg -i source-file.foo -ss 1200 -t 600 third-10-min.m4v
splitLength = 5
for i in range(int(videoLength/splitLength)):
    start =i*60
    length=splitLength*60 
    os.system("ffmpeg -i source-file.foo -ss " + str(start) + " -t " + str(length) + " clip"+str(i)+".m4v")
-----------------------
pip3 install moviepy
0-300 
300-600
600-900
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

# Replace the filename below.
required_video_file = "filename.mp4"

with open("times.txt") as f:
  times = f.readlines()

times = [x.strip() for x in times] 

for time in times:
  starttime = int(time.split("-")[0])
  endtime = int(time.split("-")[1])
  ffmpeg_extract_subclip(required_video_file, starttime, endtime, targetname=str(times.index(time)+1)+".mp4")

python split.py
-----------------------
pip3 install moviepy
0-300 
300-600
600-900
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

# Replace the filename below.
required_video_file = "filename.mp4"

with open("times.txt") as f:
  times = f.readlines()

times = [x.strip() for x in times] 

for time in times:
  starttime = int(time.split("-")[0])
  endtime = int(time.split("-")[1])
  ffmpeg_extract_subclip(required_video_file, starttime, endtime, targetname=str(times.index(time)+1)+".mp4")

python split.py
-----------------------
pip3 install moviepy
0-300 
300-600
600-900
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

# Replace the filename below.
required_video_file = "filename.mp4"

with open("times.txt") as f:
  times = f.readlines()

times = [x.strip() for x in times] 

for time in times:
  starttime = int(time.split("-")[0])
  endtime = int(time.split("-")[1])
  ffmpeg_extract_subclip(required_video_file, starttime, endtime, targetname=str(times.index(time)+1)+".mp4")

python split.py
-----------------------
pip3 install moviepy
0-300 
300-600
600-900
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

# Replace the filename below.
required_video_file = "filename.mp4"

with open("times.txt") as f:
  times = f.readlines()

times = [x.strip() for x in times] 

for time in times:
  starttime = int(time.split("-")[0])
  endtime = int(time.split("-")[1])
  ffmpeg_extract_subclip(required_video_file, starttime, endtime, targetname=str(times.index(time)+1)+".mp4")

python split.py

Discord Bot leave the VC after X Seconds with Discord.js

copy iconCopydownload iconDownload
// message.guild.id = '1234567812345678'
const queue = new Map();

// 1. set new queue
const queueContruct = {
  textChannel: message.channel,
  voiceChannel: voiceChannel,
  connection: null,
  songs: [],
  search: [],
  volume: 5,
  playing: true,
  leaveTimer: null /* 20 seconds in question */
};
queue.set('1234567812345678', queueContruct);

// 2. get queueContruct from queue
const serverQueue = queue.get('1234567812345678');
if(!serverQueue) { /* not exist */ }

// 3. delete from queue
queue.delete('1234567812345678');
const Discord = require('discord.js');
const bot = new Discord.Client();
const queue = new Map();
const prefix = "?"; // this prefix is in Question.

bot.on("message", async message => {
  // if direct-message received, message.guild could be null
  // Not handle that case.
  const serverQueue = queue.get(message.guild.id);

  if(message.content.startsWith(`${prefix}audio`)) {
    execute(message, serverQueue);
  }
});

// I assume user message is "?audio audioName"
function execute(message, serverQueue) {
  const audioName = message.content.split(' ')[1]; // "audioName"

  // check user who send message is in voiceChannel 
  const voiceChannel = message.member.voice.channel;
  if(!voiceChannel) {
    return message.channel.send("YOU ARE NOT IN VOICE CHANNEL");
  }

  // check permission
  const permissions = voiceChannel.permissionsFor(message.client.user);
  if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
    return message.channel.send("PERMISSION ERROR");
  }

  /*
    I handle only songs with google youtube api
    So, I skip how to get & push song information
  */

  if(!serverQueue) {
    // create new serverQueue

    const queueContruct = {
      textChannel: message.channel,
      voiceChannel: voiceChannel,
      connection: null,
      songs: [],
      search: [],
      volume: 5,
      playing: true
    };

    queue.set(message.guild.id, queueContruct);

    // "song" value is one of play list in my case
    // var song = {title: 'audioName', url: 'youtube-url'};
    queueContruct.songs.push(song);

    try {
      var connection = await voiceChannel.join();
      queueContruct.connection = connection;
      playStart(message.guild, queueContruct.songs[0]);
    } catch (err) {
      queue.delete(message.guild.id);
      return message.channel.send(err);
    }
  }
  else { // exist serverQueue
    // "song" value is one of play list in my case
    // var song = {title: 'audioName', url: 'youtube-url'};
    serverQueue.songs.push(song);

    if(serverQueue.songs.length == 1) {
      playStart(message.guild, serverQueue.songs[0]);
    }
  }
}

function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if(!song) {
    if(serverQueue.songs.length == 0) {
      serverQueue.leaveTimer = setTimeout(function() {
        leave_with_timeout(guild.id);
      }, 20 * 1000); // 20 seconds is for follow question
    }
    return;
  }

  // clear timer before set
  try {
    clearTimeout(serverQueue.leaveTimer);
  } catch(e) {
    // there's no leaveTimer
  }

  const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on('finish', () => {
      serverQueue.songs.shift(); // pop front
      play(guild, serverQueue.songs[0]); // play next
    })
    .on('error' error => console.log(error));
  dispatcher.setVolumeLogarithmic( 1 );
  serverQueue.textChannel.send(`Play Start ${song.title}`);
}

function leave_with_timeout(guild_id) {
  const serverQueue = queue.get(guild_id);
  if(serverQueue) {
    serverQueue.textChannel.send(`20 seconds left. Bye!`);
    serverQueue.voiceChannel.leave();
    queue.delete(guild_id);
  }
}
-----------------------
// message.guild.id = '1234567812345678'
const queue = new Map();

// 1. set new queue
const queueContruct = {
  textChannel: message.channel,
  voiceChannel: voiceChannel,
  connection: null,
  songs: [],
  search: [],
  volume: 5,
  playing: true,
  leaveTimer: null /* 20 seconds in question */
};
queue.set('1234567812345678', queueContruct);

// 2. get queueContruct from queue
const serverQueue = queue.get('1234567812345678');
if(!serverQueue) { /* not exist */ }

// 3. delete from queue
queue.delete('1234567812345678');
const Discord = require('discord.js');
const bot = new Discord.Client();
const queue = new Map();
const prefix = "?"; // this prefix is in Question.

bot.on("message", async message => {
  // if direct-message received, message.guild could be null
  // Not handle that case.
  const serverQueue = queue.get(message.guild.id);

  if(message.content.startsWith(`${prefix}audio`)) {
    execute(message, serverQueue);
  }
});

// I assume user message is "?audio audioName"
function execute(message, serverQueue) {
  const audioName = message.content.split(' ')[1]; // "audioName"

  // check user who send message is in voiceChannel 
  const voiceChannel = message.member.voice.channel;
  if(!voiceChannel) {
    return message.channel.send("YOU ARE NOT IN VOICE CHANNEL");
  }

  // check permission
  const permissions = voiceChannel.permissionsFor(message.client.user);
  if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
    return message.channel.send("PERMISSION ERROR");
  }

  /*
    I handle only songs with google youtube api
    So, I skip how to get & push song information
  */

  if(!serverQueue) {
    // create new serverQueue

    const queueContruct = {
      textChannel: message.channel,
      voiceChannel: voiceChannel,
      connection: null,
      songs: [],
      search: [],
      volume: 5,
      playing: true
    };

    queue.set(message.guild.id, queueContruct);

    // "song" value is one of play list in my case
    // var song = {title: 'audioName', url: 'youtube-url'};
    queueContruct.songs.push(song);

    try {
      var connection = await voiceChannel.join();
      queueContruct.connection = connection;
      playStart(message.guild, queueContruct.songs[0]);
    } catch (err) {
      queue.delete(message.guild.id);
      return message.channel.send(err);
    }
  }
  else { // exist serverQueue
    // "song" value is one of play list in my case
    // var song = {title: 'audioName', url: 'youtube-url'};
    serverQueue.songs.push(song);

    if(serverQueue.songs.length == 1) {
      playStart(message.guild, serverQueue.songs[0]);
    }
  }
}

function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if(!song) {
    if(serverQueue.songs.length == 0) {
      serverQueue.leaveTimer = setTimeout(function() {
        leave_with_timeout(guild.id);
      }, 20 * 1000); // 20 seconds is for follow question
    }
    return;
  }

  // clear timer before set
  try {
    clearTimeout(serverQueue.leaveTimer);
  } catch(e) {
    // there's no leaveTimer
  }

  const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on('finish', () => {
      serverQueue.songs.shift(); // pop front
      play(guild, serverQueue.songs[0]); // play next
    })
    .on('error' error => console.log(error));
  dispatcher.setVolumeLogarithmic( 1 );
  serverQueue.textChannel.send(`Play Start ${song.title}`);
}

function leave_with_timeout(guild_id) {
  const serverQueue = queue.get(guild_id);
  if(serverQueue) {
    serverQueue.textChannel.send(`20 seconds left. Bye!`);
    serverQueue.voiceChannel.leave();
    queue.delete(guild_id);
  }
}

How to get data from escaping closure into UICollectionview?

copy iconCopydownload iconDownload
func getData() {
    listFiles(){ (audioFileArray) in

    self.globalAudioFileArray = audioFileArray
self.soundBoardView.reloadData()
}

 }

Trying to retrieve an mp3 file stored in AWS S3 and load it into my React client as a Blob...it's not working

copy iconCopydownload iconDownload
<audio controls src="data:audio/mpeg;base64,blahblahblah or html src" />
 const base64MP3 = data.Body.toString('base64');
 const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        Expires: signedUrlExpireSeconds
   });
-----------------------
<audio controls src="data:audio/mpeg;base64,blahblahblah or html src" />
 const base64MP3 = data.Body.toString('base64');
 const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        Expires: signedUrlExpireSeconds
   });
-----------------------
<audio controls src="data:audio/mpeg;base64,blahblahblah or html src" />
 const base64MP3 = data.Body.toString('base64');
 const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        Expires: signedUrlExpireSeconds
   });
-----------------------
const blob = new Blob([res.data.Body], {type: 'audio/mp3' });
const blob = new Blob([new Uint8Array(res.data.Body.data)], {type: 'audio/mp3' });
res.send(data);
res.set('Content-Type', 'audio/mp3');
res.send(data.Body);
const blob = await fetch(<URL>).then(x => x.blob());
-----------------------
const blob = new Blob([res.data.Body], {type: 'audio/mp3' });
const blob = new Blob([new Uint8Array(res.data.Body.data)], {type: 'audio/mp3' });
res.send(data);
res.set('Content-Type', 'audio/mp3');
res.send(data.Body);
const blob = await fetch(<URL>).then(x => x.blob());
-----------------------
const blob = new Blob([res.data.Body], {type: 'audio/mp3' });
const blob = new Blob([new Uint8Array(res.data.Body.data)], {type: 'audio/mp3' });
res.send(data);
res.set('Content-Type', 'audio/mp3');
res.send(data.Body);
const blob = await fetch(<URL>).then(x => x.blob());
-----------------------
const blob = new Blob([res.data.Body], {type: 'audio/mp3' });
const blob = new Blob([new Uint8Array(res.data.Body.data)], {type: 'audio/mp3' });
res.send(data);
res.set('Content-Type', 'audio/mp3');
res.send(data.Body);
const blob = await fetch(<URL>).then(x => x.blob());
-----------------------
const blob = new Blob([res.data.Body], {type: 'audio/mp3' });
const blob = new Blob([new Uint8Array(res.data.Body.data)], {type: 'audio/mp3' });
res.send(data);
res.set('Content-Type', 'audio/mp3');
res.send(data.Body);
const blob = await fetch(<URL>).then(x => x.blob());

Using AVAudioPlayer in background

copy iconCopydownload iconDownload
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(String(format: "didFinishLaunchingWithOptions error: %@", error.localizedDescription))
    }
    
    return true
}
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).sink { _ in
    self.playBackground()
}
.store(in: &cancellables)
private var bgAudioPlayer = AVQueuePlayer()
func backgroundPlaylist(from audioFiles: [AudioFile]) -> [AVPlayerItem] {
    guard let firstFile = audioFiles.first else {
        // return empty array, don't wanna unwrap optionals
        return []
    }
    // declare a silence file
    let silence = AudioFile(displayName: "Silence",
                            filename: "1sec-silence")
    // start at zero
    var currentSeconds: TimeInterval = 0
    
    var playlist: [AVPlayerItem] = []
    
    // while currentSeconds is less than firstFile's fire time...
    while currentSeconds < firstFile.secondsInFuture {
        // add 1 second of silence to the playlist
        playlist.append(AVPlayerItem(url: silence.url!))
        // increment currentSeconds and we loop over again, adding more silence
        currentSeconds += 1
    }
    
    // once we're done, add the file we want to play
    playlist.append(AVPlayerItem(url: audioFiles.first!.url!))
                    
    return playlist
}
func playInBackground() {
    do {
        // make sure the sound is one
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default,
                                                        policy: .longFormAudio,
                                                        options: [])
        try AVAudioSession.sharedInstance().setActive(true)
        let playlist = backgroundPlaylist(from: backgroundPlaylist)
        bgAudioPlayer = AVQueuePlayer(items: playlist)
        bgAudioPlayer.play()
    } catch {
        // Not much to mess up, so leaving alone for now, but need to make
        // `throws` if we handle errors
        print(String(format: "playInBackground error: %@",
                        error.localizedDescription))
    }
}
-----------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(String(format: "didFinishLaunchingWithOptions error: %@", error.localizedDescription))
    }
    
    return true
}
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).sink { _ in
    self.playBackground()
}
.store(in: &cancellables)
private var bgAudioPlayer = AVQueuePlayer()
func backgroundPlaylist(from audioFiles: [AudioFile]) -> [AVPlayerItem] {
    guard let firstFile = audioFiles.first else {
        // return empty array, don't wanna unwrap optionals
        return []
    }
    // declare a silence file
    let silence = AudioFile(displayName: "Silence",
                            filename: "1sec-silence")
    // start at zero
    var currentSeconds: TimeInterval = 0
    
    var playlist: [AVPlayerItem] = []
    
    // while currentSeconds is less than firstFile's fire time...
    while currentSeconds < firstFile.secondsInFuture {
        // add 1 second of silence to the playlist
        playlist.append(AVPlayerItem(url: silence.url!))
        // increment currentSeconds and we loop over again, adding more silence
        currentSeconds += 1
    }
    
    // once we're done, add the file we want to play
    playlist.append(AVPlayerItem(url: audioFiles.first!.url!))
                    
    return playlist
}
func playInBackground() {
    do {
        // make sure the sound is one
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default,
                                                        policy: .longFormAudio,
                                                        options: [])
        try AVAudioSession.sharedInstance().setActive(true)
        let playlist = backgroundPlaylist(from: backgroundPlaylist)
        bgAudioPlayer = AVQueuePlayer(items: playlist)
        bgAudioPlayer.play()
    } catch {
        // Not much to mess up, so leaving alone for now, but need to make
        // `throws` if we handle errors
        print(String(format: "playInBackground error: %@",
                        error.localizedDescription))
    }
}
-----------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(String(format: "didFinishLaunchingWithOptions error: %@", error.localizedDescription))
    }
    
    return true
}
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).sink { _ in
    self.playBackground()
}
.store(in: &cancellables)
private var bgAudioPlayer = AVQueuePlayer()
func backgroundPlaylist(from audioFiles: [AudioFile]) -> [AVPlayerItem] {
    guard let firstFile = audioFiles.first else {
        // return empty array, don't wanna unwrap optionals
        return []
    }
    // declare a silence file
    let silence = AudioFile(displayName: "Silence",
                            filename: "1sec-silence")
    // start at zero
    var currentSeconds: TimeInterval = 0
    
    var playlist: [AVPlayerItem] = []
    
    // while currentSeconds is less than firstFile's fire time...
    while currentSeconds < firstFile.secondsInFuture {
        // add 1 second of silence to the playlist
        playlist.append(AVPlayerItem(url: silence.url!))
        // increment currentSeconds and we loop over again, adding more silence
        currentSeconds += 1
    }
    
    // once we're done, add the file we want to play
    playlist.append(AVPlayerItem(url: audioFiles.first!.url!))
                    
    return playlist
}
func playInBackground() {
    do {
        // make sure the sound is one
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default,
                                                        policy: .longFormAudio,
                                                        options: [])
        try AVAudioSession.sharedInstance().setActive(true)
        let playlist = backgroundPlaylist(from: backgroundPlaylist)
        bgAudioPlayer = AVQueuePlayer(items: playlist)
        bgAudioPlayer.play()
    } catch {
        // Not much to mess up, so leaving alone for now, but need to make
        // `throws` if we handle errors
        print(String(format: "playInBackground error: %@",
                        error.localizedDescription))
    }
}
-----------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(String(format: "didFinishLaunchingWithOptions error: %@", error.localizedDescription))
    }
    
    return true
}
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).sink { _ in
    self.playBackground()
}
.store(in: &cancellables)
private var bgAudioPlayer = AVQueuePlayer()
func backgroundPlaylist(from audioFiles: [AudioFile]) -> [AVPlayerItem] {
    guard let firstFile = audioFiles.first else {
        // return empty array, don't wanna unwrap optionals
        return []
    }
    // declare a silence file
    let silence = AudioFile(displayName: "Silence",
                            filename: "1sec-silence")
    // start at zero
    var currentSeconds: TimeInterval = 0
    
    var playlist: [AVPlayerItem] = []
    
    // while currentSeconds is less than firstFile's fire time...
    while currentSeconds < firstFile.secondsInFuture {
        // add 1 second of silence to the playlist
        playlist.append(AVPlayerItem(url: silence.url!))
        // increment currentSeconds and we loop over again, adding more silence
        currentSeconds += 1
    }
    
    // once we're done, add the file we want to play
    playlist.append(AVPlayerItem(url: audioFiles.first!.url!))
                    
    return playlist
}
func playInBackground() {
    do {
        // make sure the sound is one
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default,
                                                        policy: .longFormAudio,
                                                        options: [])
        try AVAudioSession.sharedInstance().setActive(true)
        let playlist = backgroundPlaylist(from: backgroundPlaylist)
        bgAudioPlayer = AVQueuePlayer(items: playlist)
        bgAudioPlayer.play()
    } catch {
        // Not much to mess up, so leaving alone for now, but need to make
        // `throws` if we handle errors
        print(String(format: "playInBackground error: %@",
                        error.localizedDescription))
    }
}
-----------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print(String(format: "didFinishLaunchingWithOptions error: %@", error.localizedDescription))
    }
    
    return true
}
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).sink { _ in
    self.playBackground()
}
.store(in: &cancellables)
private var bgAudioPlayer = AVQueuePlayer()
func backgroundPlaylist(from audioFiles: [AudioFile]) -> [AVPlayerItem] {
    guard let firstFile = audioFiles.first else {
        // return empty array, don't wanna unwrap optionals
        return []
    }
    // declare a silence file
    let silence = AudioFile(displayName: "Silence",
                            filename: "1sec-silence")
    // start at zero
    var currentSeconds: TimeInterval = 0
    
    var playlist: [AVPlayerItem] = []
    
    // while currentSeconds is less than firstFile's fire time...
    while currentSeconds < firstFile.secondsInFuture {
        // add 1 second of silence to the playlist
        playlist.append(AVPlayerItem(url: silence.url!))
        // increment currentSeconds and we loop over again, adding more silence
        currentSeconds += 1
    }
    
    // once we're done, add the file we want to play
    playlist.append(AVPlayerItem(url: audioFiles.first!.url!))
                    
    return playlist
}
func playInBackground() {
    do {
        // make sure the sound is one
        try AVAudioSession.sharedInstance().setCategory(.playback,
                                                        mode: .default,
                                                        policy: .longFormAudio,
                                                        options: [])
        try AVAudioSession.sharedInstance().setActive(true)
        let playlist = backgroundPlaylist(from: backgroundPlaylist)
        bgAudioPlayer = AVQueuePlayer(items: playlist)
        bgAudioPlayer.play()
    } catch {
        // Not much to mess up, so leaving alone for now, but need to make
        // `throws` if we handle errors
        print(String(format: "playInBackground error: %@",
                        error.localizedDescription))
    }
}

AudioKit AKPlayer can not loopback to beginning with setPosition

copy iconCopydownload iconDownload
class Beat {
    var sample: Sample!
    var onsetTime: Double

    var endTime {
        get {
            return onsetTime + sample.duration
        }
    }
}

class Sample {
    var url: URL!
    var duration: Double
}

class ViewController: UIViewController {
    var samples: [Sample] = []
    var beats: [Beat] = []

    var player: AKPlayer!
    var sequencer: AKSequencer!
}
func playCallback(status:UInt8, note:MIDINoteNumber, vel:MIDIVelocity) -> () {
    guard let status = AKMIDIStatus(byte: status),
        let type = status.type,
        type == .noteOn else { return }
    DispatchQueue.main.async {
        player.load(samples[note].url)
        player.play()
    }
}
func play(at time: Double = 0) {
    sequencer.seek(time)
    sequencer.play()
    for beat in beats {
        if beat.onsetTime < time && time < beat.endTime {
            player.load(beat.sample.url)
            player.play(from: time - beat.onsetTime)
        }
    }
}
-----------------------
class Beat {
    var sample: Sample!
    var onsetTime: Double

    var endTime {
        get {
            return onsetTime + sample.duration
        }
    }
}

class Sample {
    var url: URL!
    var duration: Double
}

class ViewController: UIViewController {
    var samples: [Sample] = []
    var beats: [Beat] = []

    var player: AKPlayer!
    var sequencer: AKSequencer!
}
func playCallback(status:UInt8, note:MIDINoteNumber, vel:MIDIVelocity) -> () {
    guard let status = AKMIDIStatus(byte: status),
        let type = status.type,
        type == .noteOn else { return }
    DispatchQueue.main.async {
        player.load(samples[note].url)
        player.play()
    }
}
func play(at time: Double = 0) {
    sequencer.seek(time)
    sequencer.play()
    for beat in beats {
        if beat.onsetTime < time && time < beat.endTime {
            player.load(beat.sample.url)
            player.play(from: time - beat.onsetTime)
        }
    }
}
-----------------------
class Beat {
    var sample: Sample!
    var onsetTime: Double

    var endTime {
        get {
            return onsetTime + sample.duration
        }
    }
}

class Sample {
    var url: URL!
    var duration: Double
}

class ViewController: UIViewController {
    var samples: [Sample] = []
    var beats: [Beat] = []

    var player: AKPlayer!
    var sequencer: AKSequencer!
}
func playCallback(status:UInt8, note:MIDINoteNumber, vel:MIDIVelocity) -> () {
    guard let status = AKMIDIStatus(byte: status),
        let type = status.type,
        type == .noteOn else { return }
    DispatchQueue.main.async {
        player.load(samples[note].url)
        player.play()
    }
}
func play(at time: Double = 0) {
    sequencer.seek(time)
    sequencer.play()
    for beat in beats {
        if beat.onsetTime < time && time < beat.endTime {
            player.load(beat.sample.url)
            player.play(from: time - beat.onsetTime)
        }
    }
}

Comparison between two lists of strings for finding substring in python

copy iconCopydownload iconDownload
if set(smaller_list).issubset(set(larger_list)):
    ## Your code

Community Discussions

Trending Discussions on AudioFile
  • Inno Setup Music Glitches when exiting
  • Play button in HTML form not playing the latest audio file, plays an old version that is meant to have been overwritten
  • I developed the recording using the JavaScript web audio API, but the sound quality is poor
  • Vue: click to play audio, click again to pause for multiple tracks
  • Cut .mp4 in pieces Python
  • Error when Converting Speech to Text in Python
  • Discord Bot leave the VC after X Seconds with Discord.js
  • How to get data from escaping closure into UICollectionview?
  • Trying to retrieve an mp3 file stored in AWS S3 and load it into my React client as a Blob...it's not working
  • How to send a PUT request with multipart/form-data body with Java Http Client?
Trending Discussions on AudioFile

QUESTION

Inno Setup Music Glitches when exiting

Asked 2021-Jun-14 at 07:52

I've used Martin Prikryl's code for my Inno Setup project. This is the link to his code:

How to make Stop and Pause/Resume/Play music buttons in Inno Setup

I used it with some tweaks on it but the problem is that the music glitches when I finish it.

For example, if the music is working while installing something and when I finally finish the setup, I still hear the glitched Audio for about 3 seconds! It's very annoying!

I think the problem is that we need to unload Music dll's before the installer finishes, as we do with the skin.

I hope you understood my situation and thanks in advance!

This is my Full code (it's not well-arranged sorry) :

[Code]
{ RedesignWizardFormBegin } // Don't remove this line!
// Don't modify this section. It is generated automatically.
var
  OldEvent_NextButtonClick: TNotifyEvent;
  OldEvent_BackButtonClick: TNotifyEvent;
  Password: TNewStaticText;
  Website: TNewButton;

procedure _NextButtonClick(Sender: TObject); forward;
procedure _BackButtonClick(Sender: TObject); forward;
procedure PasswordClick(Sender: TObject); forward;
procedure Website1Click(Sender: TObject); forward;

procedure RedesignWizardForm;
begin
  with WizardForm.NextButton do
  begin
    OldEvent_NextButtonClick := OnClick;
    OnClick := @_NextButtonClick;
  end;

  with WizardForm.BackButton do
  begin
    OldEvent_BackButtonClick := OnClick;
    OnClick := @_BackButtonClick;
  end;

  with WizardForm.WizardBitmapImage do
  begin
    Left := ScaleX(1);
    Width := ScaleX(492);
    Height := ScaleY(313);
    Visible := False;
  end;

  with WizardForm.WelcomeLabel2 do
  begin
    Enabled := False;
    ParentShowHint := False;
    Visible := False;
    Left := ScaleX(96);
    Top := ScaleY(111);
    Width := ScaleX(69);
    Height := ScaleY(47);
  end;

  with WizardForm.WelcomeLabel1 do
  begin
    Enabled := False;
    ParentShowHint := False;
    Visible := False;
    Left := ScaleX(96);
    Top := ScaleY(71);
    Width := ScaleX(109);
    Height := ScaleY(39);
  end;

  with WizardForm.PasswordEdit do
  begin
    Hint := 'Write wave4tech';
    CharCase := ecLowerCase;
    ParentShowHint := False;
    Password := False;
    ShowHint := True;
  end;

  { Password }
  Password := TNewStaticText.Create(WizardForm);
  with Password do
  begin
    Name := 'Password';
    Parent := WizardForm.PasswordPage;
    Cursor := crHand;
    Caption := ' PASSWORD IS : wave4tech ';
    Color := clGrayText;
    Font.Color := clWhite;
    Font.Height := -16;
    Font.Name := 'Tahoma';
    Font.Style := [fsBold];
    ParentColor := False;
    ParentFont := False;
    ParentShowHint := False;
    ShowHint := False;
    OnClick := @PasswordClick;
    Left := ScaleX(0);
    Top := ScaleY(80);
    Width := ScaleX(232);
    Height := ScaleY(20);
  end;

  Password.TabOrder := 3;

  with WizardForm.WizardBitmapImage2 do
  begin
    Height := ScaleY(312);
    ExtractTemporaryFile('WizardForm.WizardBitmapImage2.bmp');
    Bitmap.LoadFromFile(ExpandConstant('{tmp}\WizardForm.WizardBitmapImage2.bmp'));
  end;

  { Website }
  Website := TNewButton.Create(WizardForm);
  with Website do
  begin
    Name := 'Website';
    Parent := WizardForm;
    Left := ScaleX(153);
    Top := ScaleY(327);
    Width := ScaleX(75);
    Height := ScaleY(23);
    OnClick := @Website1Click;
  end;

  Website.TabOrder := 5;

{ ReservationBegin }
  // This part is for you. Add your specialized code here.

{ ReservationEnd }
end;
// Don't modify this section. It is generated automatically.
{ RedesignWizardFormEnd } // Don't remove this line!

procedure PasswordClick(Sender: TObject);
begin
MsgBox('The Password of this Setup is based on our Website Name. Its wave4tech in SMALL LETTERS !!', mbInformation, mb_Ok);
end;

procedure _BackButtonClick(Sender: TObject);
begin
  OldEvent_BackButtonClick(Sender);
end;

procedure _NextButtonClick(Sender: TObject);
begin
  OldEvent_NextButtonClick(Sender);
end;

// Importing Browser Identifier
procedure OpenBrowser(Url: string);
var
  ErrorCode: Integer;
begin
  ShellExec('open', Url, '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;

// Website Button Link
procedure Website1Click(Sender: TObject);
begin
OpenBrowser('https://wave4technology.blogspot.com/');
end;

// Importing LoadSkin API from ISSkin.DLL
procedure LoadSkin(lpszPath: String; lpszIniFileName: String);
external 'LoadSkin@files:isskin.dll stdcall';

// Importing UnloadSkin API from ISSkin.DLL
procedure UnloadSkin();
external 'UnloadSkin@files:isskin.dll stdcall';

// Importing ShowWindow Windows API from User32.DLL
function ShowWindow(hWnd: Integer; uType: Integer): Integer;
external 'ShowWindow@user32.dll stdcall';

function InitializeSetup(): Boolean;
begin
    ExtractTemporaryFile('VZ_Green.cjstyles');
    LoadSkin(ExpandConstant('{tmp}\VZ_Green.cjstyles'), '');
    Result := True;
end;

procedure DeinitializeSetup();
begin
  // Hide Window before unloading skin so user does not get
  // a glimpse of an unskinned window before it is closed.
  ShowWindow(StrToInt(ExpandConstant('{wizardhwnd}')), 0);
  UnloadSkin();
end;

// Music Stop-Pause/Resume
const
  BASS_SAMPLE_LOOP = 4;
  BASS_ACTIVE_STOPPED = 0;
  BASS_ACTIVE_PLAYING = 1;
  BASS_ACTIVE_STALLED = 2;
  BASS_ACTIVE_PAUSED  = 3;
  BASS_UNICODE = $80000000;
  BASS_CONFIG_GVOL_STREAM = 5;
const
  #ifndef UNICODE
    EncodingFlag = 0;
  #else
    EncodingFlag = BASS_UNICODE;
  #endif
type
  HSTREAM = DWORD;

function BASS_Init(device: LongInt; freq, flags: DWORD;
  win: HWND; clsid: Cardinal): Boolean;
  external 'BASS_Init@files:bass.dll stdcall';
function BASS_StreamCreateFile(mem: Boolean; f: string; offset1: DWORD;
  offset2: DWORD; length1: DWORD; length2: DWORD; flags: DWORD): HSTREAM;
  external 'BASS_StreamCreateFile@files:bass.dll stdcall';
function BASS_ChannelPlay(handle: DWORD; restart: Boolean): Boolean;
  external 'BASS_ChannelPlay@files:bass.dll stdcall';
function BASS_ChannelPause(handle: DWORD): Boolean;
  external 'BASS_ChannelPause@files:bass.dll stdcall';
function BASS_SetConfig(option: DWORD; value: DWORD ): Boolean;
  external 'BASS_SetConfig@files:bass.dll stdcall';
function BASS_ChannelIsActive(handle: DWORD): DWORD;
  external 'BASS_ChannelIsActive@files:bass.dll stdcall';

var
  SoundStream: HSTREAM;
  PauseResumePlayButton: TNewButton;
  StopButton: TNewButton;

procedure ResumeButtonClick(Sender: TObject); forward;

procedure PauseButtonClick(Sender: TObject);
begin
  if BASS_ChannelPause(SoundStream) then
  begin
    PauseResumePlayButton.Caption := 'Resume';
    PauseResumePlayButton.OnClick := @ResumeButtonClick;
  end;
end;

procedure ResumeButtonClick(Sender: TObject);
begin
  if BASS_ChannelPlay(SoundStream, False) then
  begin
    PauseResumePlayButton.Caption := 'Pause';
    PauseResumePlayButton.OnClick := @PauseButtonClick;
  end;
end;

procedure PlayButtonClick(Sender: TObject);
begin
  if BASS_ChannelPlay(SoundStream, True) then
  begin
    PauseResumePlayButton.Caption := 'Pause';
    PauseResumePlayButton.OnClick := @PauseButtonClick;
  end;
end;

procedure StopButtonClick(Sender: TObject);
begin
  if (BASS_ChannelIsActive(SoundStream) = BASS_ACTIVE_PAUSED) or
     BASS_ChannelPause(SoundStream) then
  begin
    PauseResumePlayButton.Caption := 'Play';
    PauseResumePlayButton.OnClick := @PlayButtonClick;
  end;
end;

// Splash Code 1
procedure ShowSplashScreen(p1:HWND;p2:string;p3,p4,p5,p6,p7:integer;p8:boolean;p9:Cardinal;p10:integer); external 'ShowSplashScreen@files:isgsg.dll stdcall delayload';

procedure InitializeWizard();
begin
  // Splash Code 2
  ExtractTemporaryFile('Splash.png');
  ShowSplashScreen(WizardForm.Handle,ExpandConstant('{tmp}\Splash.png'),1000,3000,1000,0,255,True,$FFFFFF,10);
  
  RedesignWizardForm;
  with WizardForm.WizardBitmapImage do
  begin
    Width := ScaleX(492);
    Visible := True;
  end;

  with WizardForm.WelcomeLabel2 do
  begin
    Visible := False;
  end;

  with WizardForm.WelcomeLabel1 do
  begin
    Visible := False;
  end;
  if BASS_Init(-1, 44100, 0, 0, 0) then
  begin
    ExtractTemporaryFile('AudioFile.mp3');
    SoundStream :=
      BASS_StreamCreateFile(
        False, ExpandConstant('{tmp}\AudioFile.mp3'), 0, 0, 0, 0,
        EncodingFlag or BASS_SAMPLE_LOOP);

    if SoundStream <> 0 then
    begin
      BASS_SetConfig(BASS_CONFIG_GVOL_STREAM, 2500);

      if BASS_ChannelPlay(SoundStream, False) then
      begin
        StopButton := TNewButton.Create(WizardForm);
        StopButton.Parent := WizardForm;
        StopButton.Left :=
          WizardForm.ClientWidth -
          WizardForm.CancelButton.Left -  WizardForm.CancelButton.Width;
        StopButton.Top := WizardForm.CancelButton.Top;
        StopButton.Width :=  WizardForm.CancelButton.Width;
        StopButton.Height := WizardForm.CancelButton.Height;
        StopButton.Caption := 'Stop Music';
        StopButton.OnClick := @StopButtonClick;

          PauseResumePlayButton := TNewButton.Create(WizardForm);
  PauseResumePlayButton.Parent := WizardForm;
  PauseResumePlayButton.Left := ScaleX(80);
  PauseResumePlayButton.Top := ScaleY(327);
  PauseResumePlayButton.Width := ScaleX(75);
  PauseResumePlayButton.Height := ScaleY(23);
  PauseResumePlayButton.Caption := 'Pause Music';
  PauseResumePlayButton.OnClick := @PauseButtonClick;
      end;
    end;
  end;
end;

ANSWER

Answered 2021-Jun-14 at 07:52

If you want to stop the music, when the installer is closing, just use the same code you already have in StopButtonClick from DeinitializeSetup:

procedure DeinitializeSetup();
begin
  if (SoundStream <> 0) and
     (BASS_ChannelIsActive(SoundStream) <> BASS_ACTIVE_PAUSED) then
  begin
    BASS_ChannelPause(SoundStream);
  end;

  // Hide Window before unloading skin so user does not get
  // a glimpse of an unskinned window before it is closed.
  ShowWindow(StrToInt(ExpandConstant('{wizardhwnd}')), 0);
  UnloadSkin();
end;

Source https://stackoverflow.com/questions/67944508

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install AudioFile

You can download it from GitHub.

Support

Multichannel (i.e. >2 channels) audio file support (Sidelobe)Read/write of iXML data chunks (mynameisjohn)Remove warnings (Abhinav1997)Better support on Ubuntu (BenjaminHinchliff)Faster loading of audio files (helloimmatt)Improvements to Github Actions workflow (emiro85)Pull request review (MatthieuHernandez)

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with AudioFile
Compare Audio Utils Libraries with Highest Support
Compare Audio Utils Libraries with Highest Quality
Compare Audio Utils Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.