Skip to content

Commit

Permalink
Merge pull request #55 from riderx/master
Browse files Browse the repository at this point in the history
Fix stops the background music (updated)
  • Loading branch information
bazuka5801 authored Jul 26, 2022
2 parents 7a1afd9 + 2978071 commit b13bd91
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 54 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,10 @@ isPlaying(options: { assetId: string; }) => Promise<{ isPlaying: boolean; }>

#### ConfigureOptions

| Prop | Type |
| ---------- | -------------------- |
| **`fade`** | <code>boolean</code> |
| Prop | Type | Description |
| ---------- | -------------------- | -------------------- |
| **`fade`** | <code>boolean</code> | A bool indicating whether or not to fade audio. By default - <code>true</code>
| **`focus`** | <code>boolean</code> | A bool indicating whether or not to disable mixed audio. By default - <code>true</code>


#### PreloadOptions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class Constant {
public static final String ASSET_ID = "assetId";
public static final String ASSET_PATH = "assetPath";
public static final String OPT_FADE_MUSIC = "fade";
public static final String OPT_FOCUS_AUDIO = "focus";
public static final String VOLUME = "volume";
public static final String AUDIO_CHANNEL_NUM = "audioChannelNum";
public static final String LOOP = "loop";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import static com.getcapacitor.community.audio.Constant.ERROR_AUDIO_ID_MISSING;
import static com.getcapacitor.community.audio.Constant.LOOP;
import static com.getcapacitor.community.audio.Constant.OPT_FADE_MUSIC;
import static com.getcapacitor.community.audio.Constant.OPT_FOCUS_AUDIO;
import static com.getcapacitor.community.audio.Constant.VOLUME;

import android.Manifest;
Expand Down Expand Up @@ -48,17 +49,17 @@ public class NativeAudio
private static HashMap<String, AudioAsset> audioAssetList;
private static ArrayList<AudioAsset> resumeList;
private boolean fadeMusic = false;
private AudioManager audioManager;

@Override
public void load() {
super.load();

AudioManager audioManager = (AudioManager) getBridge()
this.audioManager = (AudioManager) getBridge()
.getActivity()
.getSystemService(Context.AUDIO_SERVICE);

if (audioManager != null) {
int result = audioManager.requestAudioFocus(
if (this.audioManager != null) {
this.audioManager.requestAudioFocus(
this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
Expand Down Expand Up @@ -129,6 +130,18 @@ public void configure(PluginCall call) {

if (call.hasOption(OPT_FADE_MUSIC)) this.fadeMusic =
call.getBoolean(OPT_FADE_MUSIC);

if (call.hasOption(OPT_FOCUS_AUDIO) && this.audioManager != null) {
if (call.getBoolean(OPT_FOCUS_AUDIO)) {
this.audioManager.requestAudioFocus(
this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
);
} else {
this.audioManager.abandonAudioFocus(this);
}
}
}

@PluginMethod
Expand Down
3 changes: 2 additions & 1 deletion ios/Plugin/Constant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@

public class Constant {
public static let FadeKey = "fade"
public static let FocusAudio = "focus"
public static let AssetPathKey = "assetPath"
public static let AssetIdKey = "assetId"
public static let Volume = "volume"
public static let Loop = "loop"

public static let ErrorAssetId = "Asset Id is missing"
public static let ErrorAssetPath = "Asset Path is missing"
public static let ErrorAssetNotFound = "Asset is not loaded"
Expand Down
97 changes: 51 additions & 46 deletions ios/Plugin/Plugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,60 +13,68 @@ enum MyError: Error {
*/
@objc(NativeAudio)
public class NativeAudio: CAPPlugin {

var audioList: [String : Any] = [:]
var fadeMusic = false

var session = AVAudioSession.sharedInstance()

public override func load() {
super.load()

self.fadeMusic = false

do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSession.Category.playback)
try session.setActive(false)
try self.session.setCategory(AVAudioSession.Category.playback)
try self.session.setActive(false)
} catch {
print("Failed to ")
print("Failed to set session category")
}
}

@objc func configure(_ call: CAPPluginCall) {
let fade: Bool = call.getBool(Constant.FadeKey) ?? false

fadeMusic = fade
if let fade = call.getBool(Constant.FadeKey) {
self.fadeMusic = fade
}
if let focus = call.getBool(Constant.FocusAudio) {
do {
if focus {
try self.session.setCategory(AVAudioSession.Category.playback)
} else {
try self.session.setCategory(AVAudioSession.Category.ambient)
}
} catch {
print("Failed to set setCategory audio")
}
}
}

@objc func preload(_ call: CAPPluginCall) {
preloadAsset(call, isComplex: true)
}

@objc func play(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
let time = call.getDouble("time") ?? 0
if audioId != "" {
let queue = DispatchQueue(label: "com.getcapacitor.community.audio.complex.queue", qos: .userInitiated)

queue.async {
if self.audioList.count > 0 {
let asset = self.audioList[audioId]

if asset != nil {
if asset is AudioAsset {
let audioAsset = asset as? AudioAsset

if self.fadeMusic {
audioAsset?.playWithFade(time: time)
} else {
audioAsset?.play(time: time)
}

call.resolve()
} else if (asset is Int32) {
let audioAsset = asset as? NSNumber ?? 0

AudioServicesPlaySystemSound(SystemSoundID(audioAsset.intValue ))

call.resolve()
} else {
call.reject(Constant.ErrorAssetNotFound)
Expand All @@ -76,7 +84,7 @@ public class NativeAudio: CAPPlugin {
}
}
}

@objc private func getAudioAsset(_ call: CAPPluginCall) -> AudioAsset? {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
if audioId == "" {
Expand All @@ -92,8 +100,8 @@ public class NativeAudio: CAPPlugin {
call.reject(Constant.ErrorAssetNotFound + " - " + audioId)
return nil
}


@objc func getDuration(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
Expand All @@ -103,12 +111,12 @@ public class NativeAudio: CAPPlugin {
"duration": audioAsset.getDuration()
])
}

@objc func getCurrentTime(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

call.resolve([
"currentTime": audioAsset.getCurrentTime()
])
Expand All @@ -122,7 +130,7 @@ public class NativeAudio: CAPPlugin {
audioAsset.resume()
call.resolve()
}

@objc func pause(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
Expand All @@ -131,27 +139,27 @@ public class NativeAudio: CAPPlugin {
audioAsset.pause()
call.resolve()
}

@objc func stop(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""

do {
try stopAudio(audioId: audioId)
call.resolve()
} catch {
call.reject(Constant.ErrorAssetNotFound)
}
}

@objc func loop(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

audioAsset.loop()
call.resolve()
}

@objc func unload(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
if self.audioList.count > 0 {
Expand All @@ -162,21 +170,20 @@ public class NativeAudio: CAPPlugin {
self.audioList[audioId] = nil
}
}

call.resolve()
}

@objc func setVolume(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

let volume = call.getFloat(Constant.Volume) ?? 1.0

audioAsset.setVolume(volume: volume as NSNumber)
call.resolve()
}

@objc func isPlaying(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
Expand All @@ -186,18 +193,17 @@ public class NativeAudio: CAPPlugin {
"isPlaying": audioAsset.isPlaying()
])
}



private func preloadAsset(_ call: CAPPluginCall, isComplex complex: Bool) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
let channels: NSNumber?
let volume: Float?
let delay: NSNumber?
let isUrl: Bool?

if audioId != "" {
let assetPath: String = call.getString(Constant.AssetPathKey) ?? ""

if (complex) {
volume = call.getFloat("volume") ?? 1.0
channels = NSNumber(value: call.getInt("channels") ?? 1)
Expand All @@ -209,14 +215,14 @@ public class NativeAudio: CAPPlugin {
delay = 0
isUrl = false
}

if audioList.isEmpty {
audioList = [:]
}

let asset = audioList[audioId]
let queue = DispatchQueue(label: "com.getcapacitor.community.audio.simple.queue", qos: .userInitiated)

queue.async {
if asset == nil {
var basePath: String?
Expand All @@ -227,13 +233,12 @@ public class NativeAudio: CAPPlugin {
let url = URL(string: assetPath)
basePath = url!.path
}

if FileManager.default.fileExists(atPath: basePath ?? "") {
if !complex {
let pathUrl = URL(fileURLWithPath: basePath ?? "")
let soundFileUrl: CFURL = CFBridgingRetain(pathUrl) as! CFURL
var soundId = SystemSoundID()

AudioServicesCreateSystemSoundID(soundFileUrl, &soundId)
self.audioList[audioId] = NSNumber(value: Int32(soundId))
call.resolve()
Expand All @@ -251,15 +256,15 @@ public class NativeAudio: CAPPlugin {
}
}
}

private func stopAudio(audioId: String) throws {
if self.audioList.count > 0 {
let asset = self.audioList[audioId]

if asset != nil {
if asset is AudioAsset {
let audioAsset = asset as? AudioAsset

if self.fadeMusic {
audioAsset?.playWithFade(time: audioAsset?.getCurrentTime() ?? 0)
} else {
Expand Down
1 change: 1 addition & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface NativeAudio {

export interface ConfigureOptions {
fade?: boolean;
focus?: boolean;
}

export interface PreloadOptions {
Expand Down

0 comments on commit b13bd91

Please sign in to comment.