2016-11-13 3 views
0

First, this is how my app looks likeВоспроизведение различных звуков в TableView

Теперь я хочу, чтобы играть различные звуки при нажатии кнопки внутри этих ячеек таблицы просмотра. Я очень новичок в программировании, и я не мог понять, как это сделать. Я создал массив для своих звуковых файлов, но я не знаю, как назначить их этим кнопкам подряд. Большое спасибо за вашу помощь

И ЭТО МОЙ КОД

import UIKit 
import AVFoundation 

class ViewController6: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    var audioPlayer = AVAudioPlayer() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


//Array of Rifles 

    var arrayOfRifles = ["AK47", "AUGA1", "FAMAS", "G36K", "K1A", "K2", "M4A1", "M4Silencer", "M16", "M60", "MicroGALIL", "QBZ95", "RPK", "ScarHeavy", "Scarlight", "SG552", "TAR21", "Tommy", "Type89", "XM8"] 
    var buttonDataRifles = ["AK47", "AUGA1", "FAMAS", "G36K", "K1A", "K2", "M4A1", "M4Silencer", "M16", "M60", "MicroGALIL", "QBZ95", "RPK", "ScarHeavy", "Scarlight", "SG552", "TAR21", "Tommy", "Type89", "XM8"] 

    var soundsArray: [NSURL] = [ 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "AK47", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "AUGA1", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "FAMAS", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "G36K", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "K1A", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "K2", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "M4A1", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "M4Silencer", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "M16", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "M60", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "MicroGALIL", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "QBZ95", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "RPK", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "ScarHeavy", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "ScarLight", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "SG552", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "TAR21", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "Tommy", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "Type89", ofType: "mp3")!), 
    NSURL(fileURLWithPath: Bundle.main.path(forResource: "XM8", ofType: "mp3")!) 
    ] 




//Functions for tableView 

    //Cell - For Rifles 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return (arrayOfRifles.count) 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell6 = tableView.dequeueReusableCell(withIdentifier: "cell6", for: indexPath) as! ViewControllerTableViewCell6 

     cell6.myImage.image = UIImage(named: arrayOfRifles[indexPath.row] + ".jpg") 
     cell6.myButton.setTitle(buttonDataRifles[indexPath.row], for: UIControlState.normal) 
     return (cell6) 

     cell6.myButton.tag = indexPath.row 
     cell6.myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)} 

    @IBAction func buttonAction(_ sender: UIButton) { 

     print("Button tapped") 
     let tapedIndex = sender as UIButton 
     let getUrl = soundsArray[tapedIndex] as! NSURL 


    } 


} 

ответ

0

Прежде всего, вам нужно добавить действие на кнопку и назначить какой-то тег к этой кнопке, чтобы определить, какой из clicked.do код на cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

cell6.myButton.tag = indexPath.row 
cell6.myButton.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)} 

func buttonAction(sender: UIButton!) 
{ 
print("Button tapped") 
let tapedIndex = sender as! UIButton 
let getUrl = buttonDataRifles[tapedIndex.tag] as! NSURL 
} 
+0

Что именно вы имеете в виду под «назначить какой-то тэг этой кнопке, чтобы определить, на какой щелчок»? –

+0

Мы должны назначить здесь cell6.myButton.tag = indexPath.row как тег, поэтому всякий раз, когда мы нажимаем только на строку кнопки, мы можем определить, на какую кнопку щелкнуть по основанию, мы можем воспроизводить песню этой строки. – Bucket

+0

let getUrl = soundsArray [tapedIndex] as! NSURL Я получил ошибку в этой строке, в которой говорится: «Нельзя индексировать значение типа« NSURL »с индексом типа« UIButton » –

0

Если u'r звучит не более 30 сек я предлагаю использовать AudioToolbox. Эта структура имеет специально разработанные функции для этой цели.

Objective-C

  1. структура импорта

    #import <AudioToolbox/AudioToolbox.h> 
    
  2. сделать ссылку для звука с созданием SystemSoundID как

    @property (assign, nonatomic) SystemSoundID soundIDOne; 
    
  3. Подготовка you'r sonds в очень begginning

    AudioServicesCreateSystemSoundID ((__bridge CFURLRef)([[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Swish" ofType:@"wav"]]), &_soundIDDone); 
    
  4. Play звук

    AudioServicesPlaySystemSound(_soundIDOne); 
    
  5. Если и нужно завершение - добавить обработчик

    AudioServicesAddSystemSoundCompletion(_soundIDOne, NULL, NULL, playSoundFinished, NULL); 
    
    
    void playSoundFinished (SystemSoundID sound, void *data) { 
        //do stuff here 
    } 
    

Swift 2,2

import AudioToolbox 

    private var soundID:SystemSoundID? 

    if let filePath = NSBundle.mainBundle().pathForResource("name", ofType: "type") { 
     let pathToResource = NSURL(fileURLWithPath: filePath) 
     soundID = 0 
     if var soundID = soundID { 
      AudioServicesCreateSystemSoundID(pathToResource, &soundID) 
     } 
    } 

    if var soundID = soundID { 
     AudioServicesPlaySystemSound(soundID) 
    } 

    //or create extension 

    extension SystemSoundID { 
     static func playSound(soundName: String, fileExtension: String) { 
      var soundID: SystemSoundID = 0 
      if let filePath = NSBundle.mainBundle().pathForResource(soundName, ofType: fileExtension) { 
       let pathToResource = NSURL(fileURLWithPath: filePath) 
       AudioServicesCreateSystemSoundID(pathToResource, &soundID) 
       AudioServicesPlaySystemSound(soundID) 
      } 
     } 
    } 

    //and usage 

    SystemSoundID.playSound("soundFileName", fileExtension: "extension") 

Для более взгляда here

В случае, если и хотят, чтобы использовать AVFoundation вместо кода будет как:

import AVFoundation 

    var audioPlayer = AVAudioPlayer() //create player 

    //create all path to y'r resources 

    var path:[NSURL] = [] 

    if let filePath = NSBundle.mainBundle().pathForResource("soundName", ofType: "fileExtension") { 
     let pathToResource = NSURL(fileURLWithPath: filePath) 
     path.append(pathToResource) 
    } 

    //in the very start 
    do { 
     if let selectedPath = path.first { 
      audioPlayer = try AVAudioPlayer(contentsOfURL: selectedPath) 
      audioPlayer.prepareToPlay() 
     } 
    } catch { 
     print(error) 
    } 

    audioPlayer.play() 

В этом случае, вы можете получить некоторую задержку перед воспроизводится звук из-за необходимости prepareToPlay для AVAudioPlayer , чтобы быть уверенным в том, что u может воспроизводить звук, вам нужно немного более сложную настройку AVPlayer с наблюдением за status плеера, если вы, как и u, можете ссылаться на this link. В любом случае, если у вас есть файлы с небольшой продолжительностью, эта задержка может быть очень маленькой или даже отсутствовать, так как для меня это не является предпочтительным способом воспроизведения большого количества звуковых файлов по причине, описанной выше.

И по причине я не могу скажите u о AVFoundationQueuePlayer, это также хорошее решение. Here is Apple Образец ссылки

Смежные вопросы