↑クリックして拡大
↑クリックして拡大
↑クリックして拡大
↑クリックして拡大

頭痛が減ったので共有です!

rebuild.fmを応援しています!

HOME > AVAudioPlayerで効果音を鳴らす

AVAudioPlayerで効果音を鳴らす

簡単な効果音を鳴らすためのサンプルソースです。移動するとき,ボタンを押すとき,ドアを開けるとき等多彩なシチュエーションにご利用ください。
参考(英語): AVFoundation Framework Reference AVAudioPlayer Class Reference

おっさんの顔と音符のイラスト

サンプル構文


//hoge.wavを再生するソースです
var audioPlayer:AVAudioPlayer = AVAudioPlayer();
var sound_data = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("hoge", ofType: "wav")!);
audioPlayer = AVAudioPlayer(contentsOfURL: sound_data, error: nil);
audioPlayer.prepareToPlay();

※注意①:上記のhoge.wavはプロジェクトに取り込んでいるhoge.wavを指定しています。もしネットワーク経由等でのアクセスであれば微調整してください。

AVAudioPlayerUtil例文

AVAudioPlayerUtil.swiftをダウンロードする。(ご自由にご利用ください)

import AVFoundation

struct AVAudioPlayerUtil {
    
    static var audioPlayer:AVAudioPlayer = AVAudioPlayer();
    static var sound_data:NSURL = NSURL();
    
    static func setValue(nsurl:NSURL){
        self.sound_data = nsurl;
        self.audioPlayer = AVAudioPlayer(contentsOfURL: self.sound_data, error: nil);
        self.audioPlayer.prepareToPlay();
    }
    static func play(){
        self.audioPlayer.play();
    }
}

//利用方法
AVAudioPlayerUtil.setValue(NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("hoge", ofType: "wav")!));//ファイルセット(再生前事前準備)
AVAudioPlayerUtil.play();//再生
※注意①:このUtilは一つの効果音だけを保持する簡単なサンプルになります。もし複数の音声ファイルを保持したい場合は、soundの保存を配列にしインデックス化して再生する等微調整してご利用くださいませ。

↓こんな記事もありますよ!

2021-05-14 14:21:41

The pitfalls of Filetransfer in watchconnectivity on WatchOS. And how to avoid.

AppleWatch it succeeds with the actual machine, but if it is a simulator, it will fail、、、 When I...
2021-05-06 14:04:37

Line's animation stamp production pitfalls 、、、 failure story

I tried to make a LINE sticker during Golden Week. I made it and applied, but it was different f...
2021-04-22 14:54:53

Cool carousel carefully selected 3 points! Astringent image slider using WebGL.

I was on a trip to find a cool slider yesterday. It's simple, easy to use, and has a good de...
このエントリーをはてなブックマークに追加
右側のFacebookのLikeをクリック頂けると記事更新の際に通知されますので宜しければご利用下さい!