Воспроизведение звука системы без импорта собственных - программирование
Подтвердить что ты не робот

Воспроизведение звука системы без импорта собственных

Можно ли воспроизводить уже существующие звуки системы без импорта собственных?

4b9b3361

Ответ 1

Этот код воспроизводит звук системы Apple "Tock.aiff".. Я считаю, что вы можете воспроизводить различные звуки системы, используя этот

NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);

Смотрите этот поток

Документация Apple на звуки системы

https://developer.apple.com/documentation/audiotoolbox/system_sound_services

Ответ 2

Я нахожу этот список systemSoundID очень полезным для прямого доступа к звуковому идентификатору.
http://iphonedevwiki.net/index.php/AudioServices

Например, чтобы воспроизвести клавишу, нажмите кнопку tock.

#define systemSoundID    1104
AudioServicesPlaySystemSound (systemSoundID);

Вам также необходимо добавить структуру AudioToolbox в свой проект и добавить #include <AudioToolbox.h> в ваш .m или .h файл.

Ответ 3

Вы можете использовать это для всех системных аудио по умолчанию.

Например, для пользователя звукового сигнала нажмите эту кнопку:

AudioServicesPlaySystemSound(1104);

Для положительных звуков используйте это:

 AudioServicesPlaySystemSound(1054);

И, отрицательные звуки используют это:

 AudioServicesPlaySystemSound(1053);

В полном списке вы можете увидеть здесь.

Ответ 4

Список всех системных звуков: iOSSystemSoundsLibrary

После import AVKit вы можете воспроизводить все эти звуки с помощью:

AudioServicesPlaySystemSound (systemSoundID);

Ответ 5

адаптированный из @yannc2021

http://iphonedevwiki.net/index.php/AudioServices

если вы хотите использовать системный звук в Swift

// import this
import AVFoundation

// add this method
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

// declared system sound here
let systemSoundID: SystemSoundID = 1104

// to play sound
AudioServicesPlaySystemSound (systemSoundID)

Ответ 6

Для быстрого вы можете посмотреть полный список системных звуков и рингтоны.

Изменить: Хорошо, вот самые важные строки кода из этого примера:

    ///The directories where sound files are located.
    let rootSoundDirectories: [String] = ["/Library/Ringtones", "/System/Library/Audio/UISounds"]

    ///Array to hold directories when we find them.
    var directories: [String] = []

    ///Tuple to hold directories and an array of file names within.
    var soundFiles: [(directory: String, files: [String])] = []

    //Starting with the "/Library/Ringtones" & "/System/Library/Audio/UISounds" directories, it looks for other sub-directories just one level lower and saves their relative path in directories array.
    //- URLs: All of the contents of the directory (files and sub-directories).
    func getDirectories() {
        let fileManager: NSFileManager = NSFileManager()
        for directory in rootSoundDirectories {
            let directoryURL: NSURL = NSURL(fileURLWithPath: "\(directory)", isDirectory: true)

            do {
                if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
                    var urlIsaDirectory: ObjCBool = ObjCBool(false)
                    for url in URLs {
                        if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
                            if urlIsaDirectory {
                                let directory: String = "\(url.relativePath!)"
                                let files: [String] = []
                                let newSoundFile: (directory: String, files: [String]) = (directory, files)
                                directories.append("\(directory)")
                                soundFiles.append(newSoundFile)
                            }
                        }
                    }
                }
            } catch {
                debugPrint("\(error)")
            }
        }
    }

    //For each directory, it looks at each item (file or directory) and only appends the sound files to the soundfiles[i]files array.
    //- URLs: All of the contents of the directory (files and sub-directories).
        func loadSoundFiles() {
            for i in 0...directories.count-1 {
                let fileManager: NSFileManager = NSFileManager()
                let directoryURL: NSURL = NSURL(fileURLWithPath: directories[i], isDirectory: true)

                do {
                    if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
                        var urlIsaDirectory: ObjCBool = ObjCBool(false)
                        for url in URLs {
                            if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
                                if !urlIsaDirectory {
                                    soundFiles[i].files.append("\(url.lastPathComponent!)")
                                }
                            }
                        }
                    }
                } catch {
                    debugPrint("\(error)")
                }
            }
        }

В этом примере показаны системные звуковые файлы в виде таблицы. Звуки воспроизводятся, как показано в этой функции:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //Play the sound
        let directory: String = soundFiles[indexPath.section].directory
        let fileName: String = soundFiles[indexPath.section].files[indexPath.row]
        let fileURL: NSURL = NSURL(fileURLWithPath: "\(directory)/\(fileName)")
        do {
            model.audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
            model.audioPlayer.play()
        } catch {
            debugPrint("\(error)")
        }
    }

Где model.audioPlayer - это всего лишь экземпляр AVAudioPlayer:

///Audio player responsible for playing sound files.
var audioPlayer: AVAudioPlayer = AVAudioPlayer()

Ответ 7

Swift 4 +

ПРИМЕЧАНИЕ. Попробуйте только на реальном устройстве:

import AVKit
AudioServicesPlaySystemSound(1007);

Или вы можете попробовать с URL как -

let url = URL(fileURLWithPath: "/System/Library/Audio/UISounds/payment_success.caf")
var soundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID);

https://github.com/klaas/SwiftySystemSounds/blob/master/README.md

Ответ 8

Это решение cocoa -only использует существующие аудиофайлы для воспроизведения звуков. Этот метод можно использовать для воспроизведения любого звукового файла. AVFoundation.framework нужно будет добавить к вашим фреймворкам. Вам нужно будет определить или удалить используемые мной макросы, которые являются пояснительными.

Я добавил категорию в AVAudioPlayer следующим образом:

AVAudioPlayer +.h

 #import <AVFoundation/AVAudioPlayer.h>

@interface AVAudioPlayer ( CapSpecs )
+ (AVAudioPlayer*) click;
+ (AVAudioPlayer*) tink;
+ (AVAudioPlayer*) tock;
+ (AVAudioPlayer*) withResourceName: (NSString*) aName;
@end

AVAudioPlayer +.m

 #import "AVAudioPlayer+.h"

@implementation AVAudioPlayer ( CapSpecs )
+ (AVAudioPlayer*) click {
    StaticReturn ( [AVAudioPlayer withResourceName: @"iPod Click"] );
}
+ (AVAudioPlayer*) tink {
    StaticReturn ( [AVAudioPlayer withResourceName: @"Tink"] );
}
+ (AVAudioPlayer*) tock {
    StaticReturn ( [AVAudioPlayer withResourceName: @"Tock"] );
}
+ (AVAudioPlayer*) withResourceName: (NSString*) aName {
    NSBundle* zBundle = [NSBundle bundleWithIdentifier: @"com.apple.UIKit"];
    NSURL* zURL = [zBundle URLForResource: aName withExtension: @"aiff"];
    (void) RaiseIfNil ( nil, zURL, ([SWF @"URL for %@",aName]) );
    NSError* zError = nil;
    AVAudioPlayer* zAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: zURL error: &zError];
    RaiseError ( nil, zError, @"AVAudioPlayer init error" );

#ifdef DEBUG
    //  Apple records the console dump which occurs as a bug in the iOS simulator
    //  all of the following commented code causes the BS console dump to be hidden
    int zOldConsole = dup(STDERR_FILENO);   // record the old console
    freopen("/dev/null", "a+", stderr); // send console output to nowhere
    (void)[zAudio prepareToPlay];       // create the BS dump
    fflush(stderr);             // flush the console output
    dup2(zOldConsole, STDERR_FILENO);   // restore the console output
#endif

    return zAudio;
}
@end

Ответ 9

Для Swift

import AVFoundation

func play(sound: String) {
        var soundID: SystemSoundID = SystemSoundID()
        let mainBundle = CFBundleGetMainBundle()
        if let ref = CFBundleCopyResourceURL(mainBundle, sound as CFString, nil, nil) {
            AudioServicesCreateSystemSoundID(ref, &soundID);
            AudioServicesPlaySystemSound(soundID);
        }
}

реализация @Krishnabhadra